Skip to main content
1 of 2

Scala Case Classes

Please take a look at the following Scala program and give me suggestions for improvement. I'm sure there would be plenty. This is my very first Scala code, so please don't be frustrated because of it's low quality.

abstract class Expression {
  
  def eval() : List[List[String]] = this match {
    case Identifier(token) => List(List(token))
    case Union(exprs) => exprs.flatMap(e => e.eval)
    case Sequence(exprs) => exprs.map(e => e.eval).reduceLeft(product)
    case Iteration(min, max, expr) => {
      val subResult = expr.eval;
      (min to max toList)
        .flatMap(card => List.fill(card)(subResult).foldLeft(List(List[String]()))(product))
    }
  }
  
  def product(first: List[List[String]], second: List[List[String]]) : List[List[String]] = {
    for { x <- first; y <- second} yield x ++ y
  }
}

case class Identifier(token: String) extends Expression

case class Union(subExprs: List[Expression]) extends Expression

case class Sequence(subExprs: List[Expression]) extends Expression

case class Iteration(minCard: Int, maxCard: Int, subExpr: Expression) extends Expression

object App {
  
  def main(args: Array[String]) = {
    println(
      Iteration(
        1, 2,
        Union(
          List(
            Identifier("cat"),
            Sequence(
              List(
                Identifier("dog"),
                Iteration(
                  0, 1, Identifier("pig")
                ),
                Identifier("bird")
              )
            )
          )
        )
      ).eval
    )
  }
}