A stack-safe recursive classic synchrone for-loop?
def forLoop[A, C](
from: A,
continue: A => Boolean,
next: A => A,
compute: (C, A) => C,
acc: C): C = {
@tailrec
def go(from: A, acc: C): C = {
if (continue(from))
go(next(from), compute(acc, from))
else acc
}
go(from, acc)
}
// var acc=0; for(i=0; i < 5; i++) { acc = acc + i }
println(forLoop[Int, Int](0, _ < 5, _ + 1, _ + _, 0)) // 10
println(forLoop[Int, List[Int]](0, _ < 5, _ + 1, _ :+ _, List())) // List(0, 1, 2, 3, 4)