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]:=

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]:=

GrammarApply[calc, "2 3 + * five"]
Out[2]=

In[3]:=

GrammarApply[calc, "* * * * 1 2 3 4 5"]
Out[3]=

In[4]:=

GrammarApply[calc, "1 2 3 4 5 + + + +"]
Out[4]=

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]:=

GrammarApply[calc, "2 3 + 5 *", AmbiguityFunction -> All]
Out[5]=
