我想寫一個列表的功能。斯卡拉flatten列表
object Flat {
def flatten[T](list: List[T]): List[T] = list match {
case Nil => Nil
case head :: Nil => List(head)
case head :: tail => (head match {
case l: List[T] => flatten(l)
case i => List(i)
}) ::: flatten(tail)
}
}
object Main {
def main(args: Array[String]) = {
println(Flat.flatten(List(List(1, 1), 2, List(3, List(5, 8)))))
}
}
我不知道爲什麼它不工作,則返回List(1, 1, 2, List(3, List(5, 8)))
但它應該是List(1, 1, 2, 3, 5, 8)
。
你能給我一個提示嗎?
這是一個有趣的練習。對於實際的代碼,當然,在List中有一個'flatten'方法。 – AshleyF
這在這種情況下不起作用。這裏的列表是一個'List [Any]',所以你必須從Any => TraversableOnce [_]定義一個隱式轉換來調用flatten。這一定是可能的,但我懷疑它比這個函數更簡單。 – rjsvaljean
看看編譯器的錯誤和警告:他們會給出一些很大的線索 –