Scala - 有没有办法将模式匹配转换为if / else?

时间:2013-12-08 04:57:24

标签: scala if-statement functional-programming pattern-matching

我没有尝试在Scala中实现flatten函数,但确实找到了此实现here

def flatten(xs: List[Any]): List[Any] = xs match {
case Nil => Nil
case (head: List[_]) :: tail => flatten(head) ++ flatten(tail)
case head :: tail => head :: flatten(tail)
}

现在,有没有办法用if/else来写这个?我正试图围绕模式匹配,这将有助于看到这种模式匹配的if / else实现。我知道(head: List[_]) :: tail意味着“如果xs是一个头部也是列表和尾部的列表”,但是找不到用if / else来重写它的方法。模式匹配是否与if/else相同,还是与它完全不同的结构?是否所有if / else语句都可以进行模式匹配,反之亦然?谢谢。

1 个答案:

答案 0 :(得分:1)

应该是这样的:

 if (xs.isInstanceOf[List]) {
   val lst = xs.asInstanceOf[List]
   if (lst == Nil) {
     Nil
   } else if (lst.head.isInstanceOf[List]) {
      flatten(lst.head.asInstanceOf[List]) ++ flatten(lst.tail)
   } else {
      lst.head :: flatten(lst.tail)
   }
 }