Skip to content

Instantly share code, notes, and snippets.

@liancheng
Created December 29, 2015 06:55
Show Gist options
  • Save liancheng/219dcdfb79483b1ac1e2 to your computer and use it in GitHub Desktop.
Save liancheng/219dcdfb79483b1ac1e2 to your computer and use it in GitHub Desktop.
trait Expression
trait BinaryPredicate extends Expression {
def left: Expression
def right: Expression
}
case class Literal(value: Int) extends Expression
case class Lt(left: Expression, right: Expression) extends BinaryPredicate
case class Gt(left: Expression, right: Expression) extends BinaryPredicate
case class Eq(left: Expression, right: Expression) extends BinaryPredicate
case class And(left: Expression, right: Expression) extends BinaryPredicate
case class Or(left: Expression, right: Expression) extends BinaryPredicate
object BinaryPredicate {
def unapply(e: Expression): Option[(Expression, Expression)] = e match {
case e: BinaryPredicate => Some((e.left, e.right))
case _ => None
}
// Or even simpler:
//
// def unapply(e: BinaryPredicate): Option[(Expression, Expression)] = Some((e.left, e.right))
}
val lt = Lt(Literal(1), Literal(2))
val gt = Gt(Literal(3), Literal(2))
val and = And(lt, gt)
lt match {
case BinaryPredicate(lhs, rhs) =>
println(s"left=$lhs right=$rhs")
}
gt match {
case BinaryPredicate(lhs, rhs) =>
println(s"left=$lhs right=$rhs")
}
and match {
case BinaryPredicate(lhs, rhs) =>
println(s"left=$lhs right=$rhs")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment