Example
The following Reverse Polish notation example illustrates the interpreter pattern. The grammar
expression ::= plus | minus | variable | number
defines a language which contains reverse Polish expressions like:
plus ::= expression expression '+'
minus ::= expression expression '-'
variable ::= 'a' | 'b' | 'c' | ... | 'z'
digit = '0' | '1' | ... '9'
number ::= digit | digit number
a b +
Following the interpreter pattern there is a class for each grammar rule.
a b c + -
a b + c a - -
While the interpreter pattern does not address parsing a parser is provided for completeness.
import java.util.Map; import java.util.Stack; class Evaluator implements Expression { private Expression syntaxTree; public Evaluator(String expression) { StackFinally evaluating the expression "w x z - +" with w = 5, x = 10, and z = 42.
import java.util.Map; import java.util.HashMap; public class InterpreterExample { public static void main(String args) { String expression = "w x z - +"; Evaluator sentence = new Evaluator(expression); MapRead more about this topic: Interpreter Pattern
Famous quotes containing the word example:
“Our intellect is not the most subtle, the most powerful, the most appropriate, instrument for revealing the truth. It is life that, little by little, example by example, permits us to see that what is most important to our heart, or to our mind, is learned not by reasoning but through other agencies. Then it is that the intellect, observing their superiority, abdicates its control to them upon reasoned grounds and agrees to become their collaborator and lackey.”
—Marcel Proust (18711922)