Daniel Sobral 氏は、ここでNil
、 a への初期アキュムレータとして使用できないと答えましたfold
。
Nil
アキュムレータの初期値としては機能しません
scala> xs
res9: List[Int] = List(1, 2, 3)
scala> xs.foldLeft(Nil)( (acc, elem) => elem.toString :: acc)
<console>:9: error: type mismatch;
found : List[String]
required: scala.collection.immutable.Nil.type
xs.foldLeft(Nil)( (acc, elem) => elem.toString :: acc)
しかし、合格すればうまくいきList[String]()
ます。
scala> xs.foldLeft(List[String]())( (acc, elem) => elem.toString :: acc)
res7: List[String] = List(3, 2, 1)
しかし、なぜNil
次の末尾再帰関数で使用できるのでしょうか?
scala> def toStringList(as: List[Int]): List[String] = {
| def go(bs: List[Int], acc: List[String]): List[String]= bs match {
| case Nil => acc
| case x :: xs => go(xs, x.toString :: acc)
| }
| println(as)
| go(as, Nil)
| }
toStringList: (as: List[Int])List[String]