Skip to content

Instantly share code, notes, and snippets.

@pkukielka
Created May 31, 2012 13:23
Show Gist options
  • Save pkukielka/2843401 to your computer and use it in GitHub Desktop.
Save pkukielka/2843401 to your computer and use it in GitHub Desktop.
Factorial in scala with trampolines
sealed trait Bounce[A]
case class Done[A](result: A) extends Bounce[A]
case class Call[A](thunk: () => Bounce[A]) extends Bounce[A]
def trampoline[A](bounce: Bounce[A]): A = bounce match {
case Call(thunk) => trampoline(thunk())
case Done(x) => x
}
def factorial(n: Int, sum: BigInt): Bounce[BigInt] {
if (n <= 2) Done(sum)
else Call(() => Factorial(n - 1, n * sum))
}
object Factorial extends Application {
println(trampoline(factorial(100000, 1)))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment