Einen flexiblen Rechner mit kontextfreier Grammatik erstellen
Stellen Sie einen einfachen Rechner mit Unterstützung für Infixnotation, Polnische und umgekehrte Polnische Notation bereit. Verwenden Sie den integrierten Token "SemanticNumber" und definieren Sie Regeln für den benutzerdefinierten Token "Math".
In[1]:=
![Click for copyable input](assets.de/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}
]
];
Testen Sie den Rechner.
In[2]:=
![Click for copyable input](assets.de/create-a-flexible-calculator-using-a-context-free/In_124.png)
GrammarApply[calc, "2 3 + * five"]
Out[2]=
![](assets.de/create-a-flexible-calculator-using-a-context-free/O_81.png)
In[3]:=
![Click for copyable input](assets.de/create-a-flexible-calculator-using-a-context-free/In_125.png)
GrammarApply[calc, "* * * * 1 2 3 4 5"]
Out[3]=
![](assets.de/create-a-flexible-calculator-using-a-context-free/O_82.png)
In[4]:=
![Click for copyable input](assets.de/create-a-flexible-calculator-using-a-context-free/In_126.png)
GrammarApply[calc, "1 2 3 4 5 + + + +"]
Out[4]=
![](assets.de/create-a-flexible-calculator-using-a-context-free/O_83.png)
Abhängig davon, ob Sie Infixnotation und/oder umgekehrte Polnische Notation verwenden, ist das Parsen des Inputs möglicherweise nicht eindeutig. Dies wird von der Option AmbiguityFunction gehandhabt. Das Ergebnis 16 entspricht dem Parser-Element 2 (3 + 5) *, während das Ergebnis 25 dem Parser-Element (2 3 +) 5 * entspricht.
In[5]:=
![Click for copyable input](assets.de/create-a-flexible-calculator-using-a-context-free/In_127.png)
GrammarApply[calc, "2 3 + 5 *", AmbiguityFunction -> All]
Out[5]=
![](assets.de/create-a-flexible-calculator-using-a-context-free/O_84.png)