Last active
April 16, 2018 10:23
-
-
Save sderosiaux/7c268c1b9e2e7f33da718a56c75d8b74 to your computer and use it in GitHub Desktop.
A stack-safe recursive classic synchrone for-loop?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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