Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

Chapter 15: Case Classes and Pattern Matchingย >ย 15.3 Pattern guards - Pg. 284

C HAPTER 15 ยท Case Classes and Pattern Matching 15.3 Pattern guards Sometimes, syntactic pattern matching is not precise enough. For instance, say you are given the task of formulating a simplification rule that replaces sum expressions with two identical operands such as e + e by multiplications of two, e.g., e * 2 . In the language of Expr trees, an expression like: BinOp("+", Var("x"), Var("x")) would be transformed by this rule to: BinOp("*", Var("x"), Number(2)) You might try to define this rule as follows: scala> def simplifyAdd(e: Expr) = e match { case BinOp("+", x, x) => BinOp("*", x, Number(2)) case _ => e } <console>:11: error: x is already defined as value x case BinOp("+", x, x) => BinOp("*", x, Number(2))