Wolfram言語™

自然言語計算機を作る

この例では，自然言語で数を取り，相対的優位性が異なるいくつかの中置演算子をサポートする単純な計算機を作る．

"SemanticNumber"からの組込みトークンと4つのカスタムトークンを使う．

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};```

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