Created
May 31, 2012 13:23
-
-
Save pkukielka/2843401 to your computer and use it in GitHub Desktop.
Factorial in scala with trampolines
This file contains 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 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