Created
May 24, 2011 13:22
-
-
Save adbrowne/988685 to your computer and use it in GitHub Desktop.
Pattern Matching
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
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