Skip to content

Instantly share code, notes, and snippets.

@martintrojer
Last active July 2, 2021 06:23
Show Gist options
  • Save martintrojer/5646283 to your computer and use it in GitHub Desktop.
Save martintrojer/5646283 to your computer and use it in GitHub Desktop.
expression problem
object exprPattern extends App {
sealed trait Expr
case class Add(e1: Expr, e2: Expr) extends Expr
case class Sub(e1: Expr, e2: Expr) extends Expr
case class Num(n: Int) extends Expr
def value(e: Expr): Int = e match {
case Add(e1, e2) => value(e1) + value(e2)
case Sub(e1, e2) => value(e1) - value(e2)
case Num(n) => n
}
println(value(Add(Num(1), Sub(Num(2), Num(1)))))
// Adding new cases -- hard if there are many pattern matches (every match has the full algebra)
}
object exprPoly extends App {
sealed trait Expr {
def v: Int
}
case class Add(e1: Expr, e2: Expr) extends Expr {
def v = e1.v + e2.v
}
case class Sub(e1: Expr, e2: Expr) extends Expr {
def v = e1.v - e2.v
}
case class Num(n: Int) extends Expr {
val v = n
}
def value(e: Expr): Int = e.v
println(value(Add(Num(1), Sub(Num(3), Num(1)))))
// Adding new functions -- hard if there are many functions (every case has all functions)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment