Here’s an implementation that works:
def foldRightCPS[T, U](base: U)(f: (T, => U) => U)(as: Seq[T]): U = {
import scala.util.control.TailCalls._
@annotation.tailrec
def _foldRightCPS(fu: U => TailRec[U])(as: Seq[T]): TailRec[U] = {
as match {
case Nil => fu(base)
case head +: next => _foldRightCPS(u => tailcall(fu(f(head, u))))(next)
}
}
_foldRightCPS(u => done(u))(as).result
}
It uses scala.util.control.TailCalls
. (docs)
There’s a lot to this library that I don’t understand. But could someone explain to me what it is about such an implementation that doesn’t make it subject to the same types of problems?