Skip to content

Instantly share code, notes, and snippets.

@adbrowne
Created May 24, 2011 13:22
Show Gist options
  • Save adbrowne/988685 to your computer and use it in GitHub Desktop.
Save adbrowne/988685 to your computer and use it in GitHub Desktop.
Pattern Matching
abstract class Expr
case class Var(name: String) extends Expr
case class Number(num: Double) extends Expr
case class UnOp(operator: String, arg: Expr) extends Expr
case class BinOp(operator: String, left: Expr, right: Expr) extends Expr
class Plus(left: Expr, right: Expr) extends BinOp("+", left, right)
def simplifyTop(expr: Expr): Expr = expr match {
case UnOp("-", UnOp("-", e)) => e
case BinOp("+", e, Number(0)) => e
case BinOp("*", e, Number(1)) => e
case _ => expr
}
def simplifyAll(expr: Expr): Expr = expr match {
case UnOp("-", UnOp("-", e)) => simplifyAll(e)
case BinOp("+", e, Number(0)) => simplifyAll(e)
case BinOp("*", e, Number(1)) => simplifyAll(e)
case UnOp(op, e) => UnOp(op, simplifyAll(e))
case BinOp(op, l, r) => BinOp(op, simplifyAll(l), simplifyAll(r))
case _ => expr
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment