S-99: Ninety-Nine Scala Problems
を試してみる。
// P07 (**) Flatten a nested list structure. // Example: // scala> flatten(List(List(1, 1), 2, List(3, List(5, 8)))) // res0: List[Any] = List(1, 1, 2, 3, 5, 8) def flatten(xs: List[Any]): List[Any] = { def recursive(rest: List[Any], result: List[Any]): List[Any] = rest match { case Nil => result case head :: tail => head match { case Nil => recursive(tail, result) case h :: t => recursive(tail, recursive(t, recursive(List(h), result))) case notaList => recursive(tail, result ::: List(notaList)) } case notaList => result ::: List(notaList) } recursive(xs, Nil) }
解答例
ちくしょー!反則だ(笑
No comments:
Post a Comment