开发者

Why doesn't this match?

I tried to implement 'concat' as same as Haskell's 'concat' in Scala.

But I failed to do.

$ 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>(<c开发者_Python百科onsole>)
    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))

Is this error due to Scala's bug or not ?

Thank you.


Your match includes no case for the empty list. You have a case List(List()) (perhaps better written as List(Nil)) and a case for a non-empty list. If you add "case Nil => Nil", it works.

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)

Randall Schulz

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜