Created
May 4, 2015 06:38
-
-
Save trumanw/23bac2a60961ac97f9fd to your computer and use it in GitHub Desktop.
Object Oriented Decomposition in Scala --- Matching Object With Patterns
This file contains hidden or 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
| // 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