Below is code that I’m trying to use to illustrate pattern matching :
package patternmatching
object patterntest {
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
def simplifyTop(expr: Expr): Expr = expr match {
case UnOp("-", UnOp("-", e)) => e //double negation
case BinOp("+", e, Number(0)) => e //adding zero
case BinOp("*", e, Number(1)) => e //Mutiplying by one
case _ => expr
}
def main(args: Array[String]) {
UnOp("-" , UnOp("-", e))
}
}
How can I test each of the patterns ? The line UnOp(“-” , UnOp(“-“, e))
within the main method gives an error :
not found: value e
First, replace the main method with the following one:
It will probably print something like
Number(0)which is a match to the first case expression.Personally, I like to think that cases classes constructs values and pattern match deconstructs them. In this process of deconstructing values with patter match you can also bind the pieces to variables. After a match has occurred you use these variables.
For example, in
simplifyToptheBinOp("+", e, Number(0))will match whenexpris a BinOp, itsoperatorfield has value “+” andrightfield has value “Number(0)”, theleftfield can have any instance ofExprand its value will be bound to the variablee.Another example would be
case BinOp("+", Number(l), Number(r)) => Number(l+r), this case would not only extract – the deconstruction in Scala jargon – the outer value of type BinOp but also its inner parts, which areNumbers.