Created
October 7, 2012 10:29
-
-
Save anonymous/3847798 to your computer and use it in GitHub Desktop.
Simple Non-Polymorphic Stack Machine
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
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