Wolfram Language

Text & Language Processing

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
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
GrammarApply[calc, "2 3 + * five"]
Out[2]=
In[3]:=
Click for copyable input
GrammarApply[calc, "* * * * 1 2 3 4 5"]
Out[3]=
In[4]:=
Click for copyable input
GrammarApply[calc, "1 2 3 4 5 + + + +"]
Out[4]=

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
GrammarApply[calc, "2 3 + 5 *", AmbiguityFunction -> All]
Out[5]=

Related Examples

de es fr ja ko pt-br ru zh