Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Interp {
- def lookup(x: String, nv: List[Bind]): Result = nv match {
- case h :: t => if (x == h.x) Ok(h.v) else lookup(x, t)
- case Nil => throw new InterpException(s"$x was not found in the environment") // Undef. behavior
- }
- def interp(e: ExprC, nv: List[Bind]): Result = e match {
- case NumC(n) =>
- Ok(NumV(n))
- case PlusC(l, r) =>
- interp(l, nv) match {
- case Ok(NumV(nl)) =>
- interp(r, nv) match {
- case Ok(NumV(nr)) =>
- Ok(NumV(nl + nr))
- case Ok(v) =>
- throw InterpException("expected number, but found: " + v)
- case Exc() => Exc()
- }
- case Ok(v) =>
- throw InterpException("expected number, but found: " + v)
- case Exc() => Exc()
- }
- case RaiseC() =>
- Exc()
- case HandleC(e, h) => interp(e, nv) match {
- case Ok(v) => Ok(v)
- case _ => interp(h, nv)
- }
- case IdC(x) =>
- lookup(x, nv)
- case fd@FdC(x, body) =>
- Ok(ClosV(fd, nv))
- case AppC(f, a) => interp(f, nv) match {
- case Ok(ClosV(FdC(x, body), fenv)) => interp(a, nv) match {
- case Ok(argV) => interp(body, Bind(x, argV) :: fenv)
- case Exc() => Exc()
- }
- case Exc() => Exc() // throw new InterpException(s"$f not a closure")
- }
- case LetC(x, e1, e2) => interp(e1, nv) match {
- case Ok(v) =>
- val bind = Bind(x, v)
- val newEnv = bind :: nv
- interp(e2, newEnv)
- case Exc() => Exc()
- }
- }
- }
- // DO NOT EDIT THESE DEFINITIONS
- sealed abstract class ExprC
- case class NumC(n: Int) extends ExprC // n
- case class PlusC(l: ExprC, r: ExprC) extends ExprC // (+ e1 e2)
- case class IdC (x: String) extends ExprC // x
- case class FdC (arg: String, body: ExprC) extends ExprC // (lambda (x) e)
- case class AppC (f: ExprC, a: ExprC) extends ExprC // (f a)
- case class LetC (x: String, e1: ExprC, e2: ExprC) extends ExprC // (let (x e) e)
- case class RaiseC() extends ExprC // (raise)
- case class HandleC(e: ExprC, h: ExprC) extends ExprC // (handle e e)
- sealed abstract class Value
- case class NumV(n: Int) extends Value
- case class ClosV(fdc: FdC, nv: List[Bind]) extends Value
- sealed abstract class Result
- case class Ok(v: Value) extends Result
- case class Exc() extends Result
- case class Bind(x: String, v: Value)
- case class NotImplementedException() extends RuntimeException("not implemented")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement