Skip to content

Instantly share code, notes, and snippets.

@trumanw
Created May 4, 2015 06:38
Show Gist options
  • Select an option

  • Save trumanw/23bac2a60961ac97f9fd to your computer and use it in GitHub Desktop.

Select an option

Save trumanw/23bac2a60961ac97f9fd to your computer and use it in GitHub Desktop.
Object Oriented Decomposition in Scala --- Matching Object With Patterns
// Cited from the essay "Matching Object With Patterns"
// Class hierarchy:
trait Expr {
def isVar: Boolean = false
def isNum: Boolean = false
def isMul: Boolean = false
def value: Int = throw new NullPointerException
def name: String = throw new NullPointerException
def left: Expr = throw new NullPointerException
def right: Expr = throw new NullPointerException
}
class Num(override val value: Int) extends Expr {
override def isNum = true
}
class Var(override val name: String) extends Expr {
override def isVar = true
}
class Mul(override val left: Expr, override val right: Expr) extends Expr {
override def isMul = true
}
object Decomposition extends App {
val numObj = new Num(1)
val varObj = new Var("var")
val mulObj = new Mul(numObj, varObj)
// Simplification rule:
if (mulObj.isMul) {
val leftOfMul = mulObj.left
if (leftOfMul.isNum && 1 == leftOfMul.value) {
println("The left Expr of the mul is : " + leftOfMul.value)
// leftOfMul
} else {
println("Thee left Expr of the mul is not a number object.")
// mulObj
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment