我試圖使用下面的代碼展開列表的列表。當我把它放在紙上時,它應該起作用,但我認爲我誤解了或者對列表的工作方式一無所知。任何人都可以告訴我我錯了哪裏。在Scala中使用展平方法給出了糟糕的結果,列出了列表中的列表
val a = List(List(1,2,3),List(4,5,6),List(7,8,9))
def flatten(xss : List[List[Any]]) : List[Any] = {
def flat(xs : List[Any]) : List[Any] = xs match {
case Nil => Nil
case head :: Nil=> head :: Nil
case head :: tail => head :: flat(tail)
}
xss match {
case Nil => Nil
case head :: Nil => flat(head)
case head :: tail => flat(head) :: flatten(tail)
}
}
flatten(a)
我認爲你需要採取另一種思維會話什麼壓扁列表意味着,一個好的技巧我傾向於使用的表達出來換句話說,因爲經常有一個功能實現匹配那麼好。 – johanandren
你有沒有想過使用內置的flatMap函數? – Leon
我應該實現扁平化功能而不使用扁平化方法。即使不應該使用::: – user64287