# Wolfram 语言™

## 生成自然语言计算器

In[1]:=
```tokens = {GrammarToken["SemanticNumber"], GrammarToken["Summand"], GrammarToken["Multiplicand"], GrammarToken["Addition"], GrammarToken["Multiplication"]};```

In[2]:=
```defs1 = {"Summand" -> s : (GrammarToken["Addition"] | GrammarToken["Multiplication"] | GrammarToken["SemanticNumber"]) :> s, "Multiplicand" -> m : (GrammarToken["Multiplication"] | GrammarToken["SemanticNumber"]) :> m};```

"Addition" token 与加和减相关联，并将 "Multiplication" token 与乘和除相关联. 减和除是不能交换位置的，因此需要使用 FixedOrder 保持各项的前后顺序.

In[3]:=
```defs2 = { "Addition" -> FixedOrder[a : GrammarToken["Summand"], "+", b : GrammarToken["Summand"]] :> a + b, "Addition" -> FixedOrder[a : GrammarToken["Summand"], "-", b : GrammarToken["Summand"]] :> a - b, "Multiplication" -> FixedOrder[a : GrammarToken["Multiplicand"], "*", b : GrammarToken["Multiplicand"]] :> a*b, "Multiplication" -> FixedOrder[a : GrammarToken["Multiplicand"], "/", b : GrammarToken["Multiplicand"]] :> a/b};```

GrammarRules 对象部署到 Wolfram Cloud.

In[4]:=
`calc = CloudDeploy[GrammarRules[tokens, Join[defs1, defs2]]];`

In[5]:=
`GrammarApply[calc, "one + one"]`
Out[5]=
In[6]:=
`GrammarApply[calc, "one + two + three"]`
Out[6]=
In[7]:=
`GrammarApply[calc, "five + seventeen * ten"]`
Out[7]=
In[8]:=
`GrammarApply[calc, "one hundred - one hundredth"]`
Out[8]=
In[9]:=
`GrammarApply[calc, "zero + one/forty-five"]`
Out[9]=
In[10]:=
`GrammarApply[calc, "one/forty-five - one"]`
Out[10]=