2009-11-26 159 views
1

我試圖像Scala中的Haskell's'concat'一樣實現'concat'。這爲什麼不匹配?

但我沒有做到。

$ scala 
Welcome to Scala version 2.7.7.final (Java HotSpot(TM) Client VM, Java 1.6.0_14). 
Type in expressions to have them evaluated. 
Type :help for more information. 
scala> 
scala> def concat(ll:List[List[Any]]):List[Any] = { ll match { case List(List()) => Nil; case (x::xs) => x ::: concat(xs) }} 
concat: (List[List[Any]])List[Any] 

scala> concat(List(1,2)::List(3,4)::Nil) 
scala.MatchError: List() 
    at .concat(<console>:67) 
    at .concat(<console>:67) 
    at .concat(<console>:67) 
    at .<init>(<console>:68) 
    at .<clinit>(<console>) 
    at RequestResult$.<init>(<console>:3) 
    at RequestResult$.<clinit>(<console>) 
    at RequestResult$result(<console>) 
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeM... 

scala> List(1,2)::List(3,4)::Nil 
res47: List[List[Int]] = List(List(1, 2), List(3, 4)) 

這個錯誤是由於斯卡拉的bug嗎?

謝謝。

回答

3

您的匹配不包含空列表。你有一個List List(List)(也許最好寫成List(Nil))和一個非空列表的情況。如果添加「無Nil =>無」,它就可以工作。

scala> def concat(ll:List[List[Any]]):List[Any] = { ll match { case List(Nil) => Nil; case (x::xs) => x ::: concat(xs); case Nil => Nil }} 
concat: (List[List[Any]])List[Any] 

scala> concat(List(1,2)::List(3,4)::Nil) 
res0: List[Any] = List(1, 2, 3, 4) 

蘭德爾·舒爾茨

+0

其實,這是錯誤的存在一樣有一個列表(無)的情況下。考慮下面的調用concat(List(1,2):: List():: List(3,4):: Nil)。結果將是1 :: 2 :: Nil – 2009-11-27 04:54:47

相關問題