Created
November 23, 2020 19:04
-
-
Save latant/76bbeee0aaf6bda0bbf8ee9790561bd4 to your computer and use it in GitHub Desktop.
Loop-recur in Kotlin
This file contains hidden or 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
// 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