匹配类型的头/尾模式匹配参数

Ben*_*son 1 scala pattern-matching

我正在研究九十九个Scala问题的 P07 :

P07 (**) Flatten a nested list structure.
Example:
scala> flatten(List(List(1, 1), 2, List(3, List(5, 8))))
res0: List[Any] = List(1, 1, 2, 3, 5, 8)
Run Code Online (Sandbox Code Playgroud)

我最初的解决方案是:

def flatten[A](ls : List[A]): List[A] = {
   def flattenRec[A](ls: List[A], flatList: List[A]): List[A] = ls match {
     case Nil => flatList
     case head: List[A] :: tail =>  flattenRec(head ::: flatten(tail), flatList)
     case head :: tail => flattenRec(tail, flatList :+ head)
   }
   flattenRec(ls, List[A]())
 }
Run Code Online (Sandbox Code Playgroud)

但是这不会编译,因为我不允许head在第二个case语句中指定类型.有没有办法让我这样做?

顺便说一句,推荐的解决方案使用flatMap而不是match,但我不确定为什么它甚至需要模式匹配...

Sha*_*nds 5

你可以把头部的声明括起来:

def flatten[A](ls : List[A]): List[A] = {
  def flattenRec[A](ls: List[A], flatList: List[A]): List[A] = ls match {
    case Nil => flatList
    case (head: List[A]) :: tail => flattenRec(head, flatList)
    case head :: tail => flattenRec(tail, flatList :+ head)
  }
  flattenRec(ls, List[A]())
}
Run Code Online (Sandbox Code Playgroud)

请注意,您将收到有关未选中的类型模式的警告(因为头部需要是一个列表,A而不是其他任何内容将在运行时由于擦除而丢失),您需要确保自己可以忽略(或者经历一些涉及TypeTags)的hijinks .