Last active
November 4, 2015 20:29
-
-
Save valtih1978/abc91e912e72be7bb356 to your computer and use it in GitHub Desktop.
Symbolic expressions
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
trait E { | |
def e(dict: Map[Const, Int]): Int | |
def +(another: E): E = (this, another) match { | |
case (zero, _) => another // Bug! Bug! this unintentionally redefines zero | |
case (_, zero) => this | |
case _ => Plus(this, another) | |
} | |
def *(another: E): E = { | |
def par(e: E) = e match {case e @ Plus(a,b) => Par(e); case e => e} | |
Mult(par(this), par(another)) | |
} | |
} | |
case class Const(a: Char) extends E { | |
override def toString = a toString | |
def e(dict: Map[Const, Int]): Int = dict.get(this).orElse(Some(a - '0')).get | |
} | |
case class Par(e: E) extends E { | |
override def toString = s"($e)" | |
def e(dict: Map[Const, Int]): Int = e.e(dict) | |
} | |
case class Plus(a: E, b: E) extends E { | |
override def toString = s"$a+$b" | |
def e(dict: Map[Const, Int]): Int = a.e(dict) + b.e(dict) | |
} | |
case class Mult(a: E, b: E) extends E { | |
override def toString = s"$a*$b" | |
def e(dict: Map[Const, Int]): Int = a.e(dict) * b.e(dict) | |
} | |
val q = Const('q') ; val p = Const('p') ; val one = Const('5') | |
//> q : A.Const = q | |
//| p : A.Const = p | |
//| one : A.Const = 5 | |
val env = Map(q -> 1, p -> 2) //> env : scala.collection.immutable.Map[A.Const,Int] = Map(q -> 1, p -> 2) | |
q.e(env) //> res0: Int = 1 | |
Plus(q, p) //> res1: A.Plus = q+p | |
Plus(p, one).e(env) //> res2: Int = 7 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment