Crie uma calculadora flexível usando gramática independente do contexto
Implemente uma calculadora simples que dê suporte a infixos, notação polonesa, e notação polonesa inversa. Use o elemento integrado "SemanticNumber" e defina regras para o elemento customizado "Math".
In[1]:=
![Click for copyable input](assets.pt-br/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}
]
];
Teste a calculadora.
In[2]:=
![Click for copyable input](assets.pt-br/create-a-flexible-calculator-using-a-context-free/In_124.png)
GrammarApply[calc, "2 3 + * five"]
Out[2]=
![](assets.pt-br/create-a-flexible-calculator-using-a-context-free/O_81.png)
In[3]:=
![Click for copyable input](assets.pt-br/create-a-flexible-calculator-using-a-context-free/In_125.png)
GrammarApply[calc, "* * * * 1 2 3 4 5"]
Out[3]=
![](assets.pt-br/create-a-flexible-calculator-using-a-context-free/O_82.png)
In[4]:=
![Click for copyable input](assets.pt-br/create-a-flexible-calculator-using-a-context-free/In_126.png)
GrammarApply[calc, "1 2 3 4 5 + + + +"]
Out[4]=
![](assets.pt-br/create-a-flexible-calculator-using-a-context-free/O_83.png)
Dependendo se você usar infix e/ou notação polonesa inversa, pode haver ambiguidade na análise do input. Isso é tratado pela opção AmbiguityFunction. O resultado 16 correponde à análise de 2 (3 + 5) *, enquanto o resultado 25 correspode à análise de (2 3 +) 5 *.
In[5]:=
![Click for copyable input](assets.pt-br/create-a-flexible-calculator-using-a-context-free/In_127.png)
GrammarApply[calc, "2 3 + 5 *", AmbiguityFunction -> All]
Out[5]=
![](assets.pt-br/create-a-flexible-calculator-using-a-context-free/O_84.png)