列表上的案例类和模式匹配

时间:2012-02-08 00:20:19

标签: scala pattern-matching

我想做的是简化这个表达

选项(选项(ExpList(列表(的选项(选项(VAR( “任选的”)))))))

获得类似的东西

(ExpList(列表(的(VAR( “任选的”)))))


为了简化列表中的所有表达式,匹配表达式的内容是什么样的。

这些任务的最佳做法是什么?

我试过的代码片段是这样的:

object CaseClassPatternMatching extends App {
  abstract class Expr
  case class Var(name: String) extends Expr
  case class Opt(expr: Expr) extends Expr
  case class ExpList(listExp: List[Expr]) extends Expr

  def joinOpt(feature: Expr): Expr = feature match {
    case Opt(Opt(f)) => joinOpt(Opt(f))    // Opt(Opt("test")) --> Opt("test")
    // case ExpList(list) => ????          // What to do there?
    case _ => feature
  }

  val expr1: Expr = joinOpt(Opt(Opt(Opt(Var("optional")))))
  println(Opt(Var("optional"))) 
  // Output: Opt(Var(optional))  --> That one is OK...

  val expr2: Expr = joinOpt(Opt(Opt(ExpList(List(Opt(Opt(Var("optional"))))))))
  println(expr2)
  // Output: Opt(ExpList(List(Opt(Opt(Var(optional))))))  --> Not OK...
  // How to simplify expressions inside list?
}

[编辑]

对于那些感兴趣的人,类似主题:

Scala case classes, pattern matching and varargs

2 个答案:

答案 0 :(得分:7)

您需要四个案例:

def joinOpt(feature: Expr): Expr = feature match {
                         // remove extra Opt 
                         // (you can use @ to avoid recreating Opt)
  case Opt(opt @ Opt(_)) => joinOpt(opt) 
                         // preserve single Opt
  case Opt(expr)         => Opt(joinOpt(expr)) 
                         // apply function to all elements in inner list
  case ExpList(list)     => ExpList(list map joinOpt) 
  case _ => feature
}

答案 1 :(得分:3)

好吧,我会这样写joinOpt

def joinOpt(feature: Expr): Expr = feature match {
  case Opt(Opt(f))   => joinOpt(Opt(f))    // Opt(Opt("test")) --> Opt("test")
  case ExpList(list) => ExpList(list map joinOpt)
  case other         => other
}