Skip to content

Instantly share code, notes, and snippets.

@sderosiaux
Last active April 16, 2018 10:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sderosiaux/7c268c1b9e2e7f33da718a56c75d8b74 to your computer and use it in GitHub Desktop.
Save sderosiaux/7c268c1b9e2e7f33da718a56c75d8b74 to your computer and use it in GitHub Desktop.
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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment