Created
February 26, 2016 11:15
-
-
Save buzztaiki/0f1715876083b64e8509 to your computer and use it in GitHub Desktop.
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
sealed class Trampoline<A> { | |
class More<A>(val fn: () -> Trampoline<A>): Trampoline<A>() { | |
override fun toString() = "More" | |
} | |
class Done<A>(val a: A): Trampoline<A>() { | |
override fun toString() = "Done($a)" | |
} | |
companion object { | |
fun <A> run(fn: () -> Trampoline<A>): A = run(fn()).let { | |
when (it) { | |
is Done -> it.a | |
else -> throw Exception() | |
} | |
} | |
tailrec fun <A> run(t: Trampoline<A>): Trampoline<A> { | |
return when (t) { | |
is Done -> t | |
is More -> run(t.fn()) | |
} | |
} | |
} | |
} | |
fun odd(n: Int): Trampoline<Boolean> { | |
return when(n) { | |
0 -> Trampoline.Done(false) | |
else -> Trampoline.More { even(n - 1) } | |
} | |
} | |
fun even(n: Int): Trampoline<Boolean> { | |
return when(n) { | |
0 -> Trampoline.Done(true) | |
else -> Trampoline.More { odd(n - 1) } | |
} | |
} | |
fun main(args: Array<String>) { | |
println(Trampoline.run { odd(10000000) }) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment