2009-11-26 161 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

相关问题