Skip to content

Instantly share code, notes, and snippets.

@latant
Created November 23, 2020 19:04
Show Gist options
  • Save latant/76bbeee0aaf6bda0bbf8ee9790561bd4 to your computer and use it in GitHub Desktop.
Save latant/76bbeee0aaf6bda0bbf8ee9790561bd4 to your computer and use it in GitHub Desktop.
Loop-recur in Kotlin
// Loop-recur enables recursive programming without the need of defining a recursive function
fun <A, R> loop(a: A, action: Loop1<A, R>.(A) -> R) = Loop1(action).recur(a)
class Loop1<A, R>(private val action: Loop1<A, R>.(A) -> R) {
fun recur(a: A) = action(a)
}
fun main() {
val n = readLine()!!.toInt()
val fibn: Int = loop(n) { i ->
when (i) {
1, 2 -> 1
else -> recur(i - 1) + recur(i - 2)
}
}
println(fibn)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment