Java Reference
In-Depth Information
}
The SimplifyExprVisitor can now access a BinOp object and unwrap it:
public class SimplifyExprVisitor {
...
public Expr visit(BinOp e){
if("+".equals(e.opname) && e.right instanceof Number && ...){
return e.left;
}
return e;
}
}
14.4.2. Pattern matching to the rescue
There's a simpler solution using a feature called pattern matching. It's not available in Java, so
we're going to use small examples from the Scala programming language to exemplify pattern
matching. It will give you an idea of what could be possible in Java if pattern matching were
supported.
Given data type Expr representing arithmetic expressions, in the Scala programming language
(we use it because its syntax is the closest to Java), you can write the following code to
decompose an expression:
def simplifyExpression(expr: Expr): Expr = expr match {
case BinOp("+", e, Number(0)) => e // Adding zero
case BinOp("*", e, Number(1)) => e // Multiplying by one
case BinOp("/", e, Number(1)) => e // Dividing by one
case _ => expr
// Can't simplify expr
}
This use of pattern matching gives an extremely concise and expressive way to manipulate many
tree-like data structures. It's typically useful when building compilers or engines for processing
business rules. Note that the Scala syntax
Expression match { case Pattern => Expression ... }
is very similar to the Java syntax
 
Search WWH ::




Custom Search