Skip to content

Instantly share code, notes, and snippets.

@ariwaranosai
Created December 31, 2016 13:28
Show Gist options
  • Save ariwaranosai/0e8ea997fc3bdcb3c451763e784d77d4 to your computer and use it in GitHub Desktop.
Save ariwaranosai/0e8ea997fc3bdcb3c451763e784d77d4 to your computer and use it in GitHub Desktop.
abstract class Exp
case class Lit(n: Int) extends Exp
case class Neg(e: Exp) extends Exp
case class Add(e1: Exp, e2: Exp) extends Exp
object Exp {
implicit def toLit(n: Int): Lit = Lit(n)
def eval(e: Exp): Int = e match {
case Lit(n) => n
case Neg(e) => -eval(e)
case Add(e1, e2) => eval(e1) + eval(e2)
}
def view(e: Exp): String = e match {
case Lit(n) => n.toString
case Neg(e) => s"(-${view(e)})"
case Add(e1, e2) => s"(${view(e1)} + ${view(e2)})"
}
}
val ti1 = Add(Lit(8), Neg(Add(Lit(1), Lit(2))))
import Exp._
val ti2 = Add(8, Neg(Add(1, 2)))
eval(ti2)
object Repr {
type Repr = Int
def lit(x: Int): Repr = x
def neg(e: Repr): Repr = -e
def add(e1: Repr, e2: Repr) = e1 + e2
}
import Repr._
val tf1 = add(lit(8), neg(add(lit(1), lit(2))))
view(ti1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment