我只是想在scala上做一些工作,并试图自己实现List.concat函数。这里是可变模式匹配可变参数
def concat[A](lists : Traversable[A]*):List[A]={
println("concat called")
lists match {
case Nil => Nil
case x :: Nil => (x :\ List.empty[A])((elem,list)=> elem::list)
case x:: xs => (x :\ concat(xs:_*))((elem,list)=> elem :: list)
}
}
但是当我尝试调用此方法像
concat(List(1,2,3),List(2,3,4),List(4,5,6),List(6,7,8))
我得到错误
Exception in thread "main" scala.MatchError: WrappedArray(List(1, 2, 3), List(2, 3, 4), List(4, 5, 6), List(6, 7, 8)) (of class scala.collection.mutable.WrappedArray$ofRef)
有人可以解释我做错了什么在这里的代码? 在此先感谢
他能以及简化它做'lists.toList.flatten'但这可能WASN这点在这里:) –
当然,这就是为什么我在后期提到它:) – soon
'lists.flatMap(x => x)'=='lists.flatten' – Dima