June 2018
Intermediate to advanced
280 pages
7h 46m
English
The interpreter's grammar can be stored as a map of keywords with the corresponding action stored as a value. In Chapter 2, Creational Patterns, we used a mathematical expression evaluator that accumulates the result in a stack. This can be implemented by having the expressions stored in a map and accumulate the result by using reduce:
jshell> Map<String, IntBinaryOperator> operands = Map.of("+", (x, y) -> x + y, "-", (x, y) -> x - y)operands ==> {-=$Lambda$208/1259652483@65466a6a, +=$Lambda$207/1552978964@4ddced80}jshell> Arrays.asList("4 5 + 6 -".split(" ")).stream().reduce("0 ",(acc, x) -> {...> if (operands.containsKey(x)) {...> String[] split = acc.split(" ");...> System.out.println(acc);...> acc = split[0] + " " + operands.get(x).applyAsInt(Integer.valueOf(split[1]), ...Read now
Unlock full access