I just looked at the List.scala’s implementation of foldRight()
.
override def reverse: List[A] = {
var result: List[A] = Nil
var these = this
while (!these.isEmpty) {
result = these.head :: result
these = these.tail
}
result
}
override def foldRight[B](z: B)(op: (A, B) => B): B =
reverse.foldLeft(z)((right, left) => op(left, right))
As I understand it, calling foldRight
on a List
results in calling theList.reverse.foldLeft(...)
.
Is List.foldRight
implemented with foldLeft
in order to take advantage a single stack frame rather than using multiple stack frames with foldLeft
?