summaryrefslogtreecommitdiff
path: root/docs/examples/monads/directInterpreter.scala
blob: a80c9e4ed0c6557c86fa41458fa2ea1d1afb3f36 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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));
}