我只是想在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