diff options
author | Gilles Dubochet <gilles.dubochet@epfl.ch> | 2005-12-16 18:44:33 +0000 |
---|---|---|
committer | Gilles Dubochet <gilles.dubochet@epfl.ch> | 2005-12-16 18:44:33 +0000 |
commit | 53a3cc7b17f4cf97075b7e71720777fd84109696 (patch) | |
tree | 0cc784e0b47ea49cc151a136d19f20bfa8ee2197 /docs/examples/monads/directInterpreter.scala | |
parent | df50e05006b43b007c2587549030d24b5c154398 (diff) | |
download | scala-53a3cc7b17f4cf97075b7e71720777fd84109696.tar.gz scala-53a3cc7b17f4cf97075b7e71720777fd84109696.tar.bz2 scala-53a3cc7b17f4cf97075b7e71720777fd84109696.zip |
Created proper 'docs' folder for new layout.
Diffstat (limited to 'docs/examples/monads/directInterpreter.scala')
-rw-r--r-- | docs/examples/monads/directInterpreter.scala | 55 |
1 files changed, 55 insertions, 0 deletions
diff --git a/docs/examples/monads/directInterpreter.scala b/docs/examples/monads/directInterpreter.scala new file mode 100644 index 0000000000..0e2aae4a7b --- /dev/null +++ b/docs/examples/monads/directInterpreter.scala @@ -0,0 +1,55 @@ +object directInterpreter { + + type Name = String; + + trait Term; + case class Var(x: Name) extends Term; + case class Con(n: int) extends Term; + case class Add(l: Term, r: Term) extends Term; + case class Lam(x: Name, body: Term) extends Term; + case class App(fun: Term, arg: Term) extends Term; + + trait Value; + case object Wrong extends Value; + case class Num(n: int) extends Value; + case class Fun(f: Value => Value)extends Value; + + def showval(v: Value): String = v match { + case Wrong => "<wrong>" + case Num(n) => n.toString() + case Fun(f) => "<function>" + } + + type Environment = List[Pair[Name, Value]]; + + def lookup(x: Name, e: Environment): Value = e match { + case List() => Wrong + case Pair(y, b) :: e1 => if (x == y) b else lookup(x, e1) + } + + def add(a: Value, b: Value): Value = Pair(a, b) match { + case Pair(Num(m), Num(n)) => Num(m + n) + case _ => Wrong + } + + def apply(a: Value, b: Value) = a match { + case Fun(k) => k(b) + case _ => Wrong + } + + def interp(t: Term, e: Environment): Value = t match { + case Var(x) => lookup(x, e) + case Con(n) => Num(n) + case Add(l, r) => add(interp(l, e), interp(r, e)) + case Lam(x, t) => Fun(a => interp(t, Pair(x, a) :: e)) + case App(f, t) => apply(interp(f, e), interp(t, e)) + } + + def test(t: Term): String = + showval(interp(t, List())); + + val term0 = App(Lam("x", Add(Var("x"), Var("x"))), Add(Con(10), Con(11))); + + def main(args: Array[String]) = + System.out.println(test(term0)); +} |