Skip to content

Instantly share code, notes, and snippets.

@buzztaiki
Created February 26, 2016 11:15
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save buzztaiki/0f1715876083b64e8509 to your computer and use it in GitHub Desktop.
Save buzztaiki/0f1715876083b64e8509 to your computer and use it in GitHub Desktop.
kotlinでとらんぽりん
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