summaryrefslogtreecommitdiff
path: root/docs/examples/parsing/lambda/TestSyntax.scala
blob: 7edca6ccdc030ac937a237d4c40b96f2994b3cc7 (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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package examples.parsing.lambda

/**
 * Parser for an untyped lambda calculus: abstract syntax tree
 *
 * @author Miles Sabin (adapted slightly by Adriaan Moors)
 */
trait TestSyntax 
{
  trait Term 
  
  case class Unit extends Term
  {
    override def toString = "unit"
  }
  
  case class Lit(n: int) extends Term
  {
    override def toString = n.toString
  }
  
  case class Bool(b: boolean) extends Term
  {
    override def toString = b.toString
  }
  
  case class Name(name: String) extends Term
  {
    override def toString = name
  }

  case class Ref(n: Name) extends Term
  {
    def value = n
  }
  
  case class Lam(n: Name, l: Term) extends Term
  {
    override def toString = "(\\ "+n+" -> "+l+")"
  } 
  
  case class App(t1: Term, t2: Term) extends Term
  {
    override def toString = "("+t1+" "+t2+")"
  } 
  
  case class Let(n: Name, t1: Term, t2: Term) extends Term
  {
    override def toString = "let "+n+" = "+t1+" in "+t2
  }
  
  case class If(c: Term, t1: Term, t2: Term) extends Term
  {
    override def toString = "if "+c+" then "+t1+" else "+t2
  }
  
  trait PrimTerm extends Term
  {
    def apply(n: Lit) : Term
  }

  case class PrimPlus extends PrimTerm
  {
    def apply(x: Lit) = new PrimTerm { def apply(y: Lit) = Lit(x.n+y.n) }
  }

  case class PrimMinus extends PrimTerm
  {
    def apply(x: Lit) = new PrimTerm { def apply(y: Lit) = Lit(x.n-y.n) }
  }
  
  case class PrimMultiply extends PrimTerm
  {
    def apply(x: Lit) = new PrimTerm { def apply(y: Lit) = Lit(x.n*y.n) }
  }

  case class PrimDivide extends PrimTerm
  {
    def apply(x: Lit) = new PrimTerm { def apply(y: Lit) = Lit(x.n/y.n) }
  }

  case class PrimEquals extends PrimTerm
  {
    def apply(x: Lit) = new PrimTerm { def apply(y: Lit) = Bool(x.n == y.n) }
  }
}