2015-11-02 117 views
1

我的工作问题P07的Ninety-Nine Scala Problems匹配类型

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) 

我一个解决方案,最初的尝试是:

​​

然而,这并不编译因为我不允许在第二个case声明中指定head的类型。有没有办法让我做到这一点?

顺便说一句,推荐的解决方案使用flatMap代替match,但我不知道为什么它甚至需要在这种情况下,模式匹配...

回答

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]()) 
} 

请注意,您将收到关于未选中类型模式的警告(因为头部需要是A的列表,而不是其他任何东西在运行时会由于擦除而丢失),您将需要向自己保证,你可以忽略(或通过涉及的一些hijinkss)。

+0

谢谢,我觉得有点傻不付出努力这一点。 –

0

尼斯的问题,下面的备用方案:

def flatten(a:List[Any]):List[Any] = 
    a.flatMap{ 
     case l:List[Any] => flatten(l) 
     case l => List(l) 
    }