Create a Flexible Calculator Using a Context-Free Grammar
Deploy a simple calculator that supports infix, Polish, and reverse Polish notation. Use the built-in token "SemanticNumber" and define rules for the custom token "Math".
In[1]:=
![Click for copyable input](assets.en/create-a-flexible-calculator-using-a-context-free/In_123.png)
calc = CloudDeploy[
GrammarRules[{GrammarToken["SemanticNumber"], GrammarToken["Math"]},
{"Math" -> GrammarToken["SemanticNumber"],
"Math" ->
AnyOrder[a : GrammarToken["Math"], "+",
b : GrammarToken["Math"]] :> a + b,
"Math" ->
AnyOrder[a : GrammarToken["Math"], "-",
b : GrammarToken["Math"]] :> a - b,
"Math" ->
AnyOrder[a : GrammarToken["Math"], "*",
b : GrammarToken["Math"]] :> a*b,
"Math" ->
AnyOrder[a : GrammarToken["Math"], "/",
b : GrammarToken["Math"]] :> a/b}
]
];
Try out the calculator.
In[2]:=
![Click for copyable input](assets.en/create-a-flexible-calculator-using-a-context-free/In_124.png)
GrammarApply[calc, "2 3 + * five"]
Out[2]=
![](assets.en/create-a-flexible-calculator-using-a-context-free/O_81.png)
In[3]:=
![Click for copyable input](assets.en/create-a-flexible-calculator-using-a-context-free/In_125.png)
GrammarApply[calc, "* * * * 1 2 3 4 5"]
Out[3]=
![](assets.en/create-a-flexible-calculator-using-a-context-free/O_82.png)
In[4]:=
![Click for copyable input](assets.en/create-a-flexible-calculator-using-a-context-free/In_126.png)
GrammarApply[calc, "1 2 3 4 5 + + + +"]
Out[4]=
![](assets.en/create-a-flexible-calculator-using-a-context-free/O_83.png)
Depending on whether you use infix and/or reverse Polish notation, there may be ambiguity in the parsing of the input. This is handled by the option AmbiguityFunction. The result 16 corresponds to the parsing 2 (3 + 5) *, while the result 25 corresponds to the parsing (2 3 +) 5 *.
In[5]:=
![Click for copyable input](assets.en/create-a-flexible-calculator-using-a-context-free/In_127.png)
GrammarApply[calc, "2 3 + 5 *", AmbiguityFunction -> All]
Out[5]=
![](assets.en/create-a-flexible-calculator-using-a-context-free/O_84.png)