Last active
July 2, 2021 06:23
-
-
Save martintrojer/5646283 to your computer and use it in GitHub Desktop.
expression problem
This file contains hidden or 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
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) | |
} |
This file contains hidden or 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
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