Skip to content

Instantly share code, notes, and snippets.

@trumanw
Created May 4, 2015 06:45
Show Gist options
  • Save trumanw/a6e731c39459bc830f69 to your computer and use it in GitHub Desktop.
Save trumanw/a6e731c39459bc830f69 to your computer and use it in GitHub Desktop.
Extractors in Scala --- Matching Object With Patterns
// Cited from the essay "Matching Object With Patterns"
// Class hierarchy:
trait Expr
class Num(val value: Int) extends Expr
class Var(val name: String) extends Expr
class Mul(val left: Expr, val right: Expr) extends Expr
// Extractors here:
// apply is the injection
// unapply is the extraction
object Num {
def apply(value: Int) = new Num(value)
def unapply(n: Num) = Some(n.value)
}
object Var {
def apply(name: String) = new Var(name)
def unapply(v: Var) = Some(v.name)
}
object Mul {
def apply(left: Expr, right: Expr) = new Mul(left, right)
def unapply(m: Mul) = Some(m.left, m.right)
///// --
// Removing the target type from the unapply method
// to hide the underlying representation below
///// --
// def unapply(x: Expr) = x match {
// case m: Mul => Some(m.left, m.right)
// case _ => None
// }
}
object Extractor extends App {
val numObj = new Num(1)
val varObj = new Var("var")
val mulObj = new Mul(numObj, varObj)
// Simplification rule:
mulObj match {
case Mul(Num(1), Var(x)) => {
println("The right value of the mul is : " + x)
Var(x)
}
case _ => mulObj
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment