Skip to content

Instantly share code, notes, and snippets.

Created October 7, 2012 10:29
Show Gist options
  • Save anonymous/3847798 to your computer and use it in GitHub Desktop.
Save anonymous/3847798 to your computer and use it in GitHub Desktop.
Simple Non-Polymorphic Stack Machine
import language.implicitConversions
import collection.immutable.Stack
import scalaz._
import Scalaz._
sealed trait Op {
def execute(ctx: Stack[Int]): Stack[Int]
}
object Op {
def execute(ctx: Stack[Int], op: Op) = op.execute(ctx)
implicit def IntToPrimitive(i: Int) = Push(i)
implicit def ListOpPimp(ops: List[Op]) = new {
def run = ops.foldLeft(Stack[Int]()) { execute }
}
}
case class Push(i: Int) extends Op {
def execute(ctx: Stack[Int]) = ctx.push(i)
}
case class SumOp() extends Op {
def execute(ctx: Stack[Int]) = {
val (a, p) = ctx.pop2
val (b, q) = p.pop2
q.push(a + b)
}
}
object Main extends App {
import Op._
val ops = List[Op](2, 3, 5, SumOp(), SumOp())
val exe = ops.run
exe.head |> println
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment