Tail recursive version of foldRight for List?

View: New views
1 Messages — Rating Filter:   Alert me  

Tail recursive version of foldRight for List?

by Sébastien Bocq :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

Hi,

Wouldn't this version be safer?

override def foldRight[B](z: B)(f: (A, B) => B): B = this.reverse.foldLeft(z)((b, a) => f(a, b)))

(same idea for reduceRight)

The argument is the same as for trampolining: it may be less efficient but at least it will never blow up the stack.

Thanks,
Sebastien