Skip to content

Instantly share code, notes, and snippets.

@mbrc12
Created April 12, 2020 09:15
Show Gist options
  • Save mbrc12/6eb3419016d51c726d1eff04b9866b17 to your computer and use it in GitHub Desktop.
Save mbrc12/6eb3419016d51c726d1eff04b9866b17 to your computer and use it in GitHub Desktop.
Example code using Trampolines [Doesn't Work]
import mill._, scalalib._;
object cub extends ScalaModule {
def scalaVersion = "0.23.0-RC1";
def finalMainClass = "Factorial";
// def scalaVersion = "2.13.1";
}
import scala.annotation.tailrec
sealed trait Trampoline[+A]
case class Done[A](x : A) extends Trampoline[A]
case class More[A](x : () => Trampoline[A]) extends Trampoline[A]
case class Act[A, B](x : Trampoline[B], f : (B => Trampoline[A])) extends Trampoline[A]
object Runner {
@tailrec
def runT[A](c : Trampoline[A]) : A = c match {
case Done(x) => x
case More(x) => runT(x())
case Act(x, f) => x match {
case Done(y) => runT(f(y))
case More(y) => runT(Act(y(), f))
case Act(y, g) => runT(Act(y, q => Act(g(q), f)))
}
}
}
object Factorial {
import Runner._;
def tFact(n : BigInt) : Trampoline[BigInt] = {
if (n <= 1)
Done(1)
else Act(More(() => tFact(n - 1)), (p : BigInt) => Done(n * p))
}
def main(args : Array[String]) = {
println(args(1))
if (args.length < 2) {
println("Usage: .. <number>")
} else {
val n = BigInt(args(1))
println(runT(tFact(n)).toString)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment