Prolog- translating English to C

柔情痞子 提交于 2019-12-02 06:39:36

If there is a reasonable small number of patterns, you could do:

english2C([add,X,to,Y], R) :- R is X+Y.
english2C([add,A,to,B,',',then,subtract,C], R) :- R is A+B-C.

edit

Those rules above compute the value. To translate, we can use DCG for matching, it's working 'backwards' as well.

english2C(In, R) :- phrase(toe(R), In, []).

toe(X+Y) --> [add,X,to,Y].
toe(X*Y) --> [multiply,X,by,Y].
toe(L-R) --> toe(L), [',',then,subtract,R].

test:

?- english2C(X,3+6).
X = [add, 3, to, 6].

edit sorry, I forgot a cut. With that added, I get

?- english2C([add,3,to,5,',',then,subtract,4],X).
X = 3+5-4.

?- english2C(L,3+5-4).
L = [add, 3, to, 5, ',', then, subtract, 4].

without, there is the loop after ;

?- english2C([add,3,to,5,',',then,subtract,4],X).
X = 3+5-4 ;
^CAction (h for help) ? goals
[698,875] toe(_G2096630, [add, 3, to, 5, ',', then, subtract, 4], _G2096652)
[698,874] toe('<garbage_collected>', '<garbage_collected>', _G2096652)
...

It's a single point change: do you prefer to find it yourself?

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!