Prolog Prefix Expression

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-24 05:53:13

问题


I'm able to get the sum from the prefix expression but whenever I add a list within a list the program doesn't run.

expr(Z) --> num(Z).
expr(Z) --> [+], num(X), expr(Y), {Z is X+Y}.
expr(Z) --> [-], num(X), expr(Y), {Z is X-Y}.
num(D) --> [D], {number(D)}.

calculate(L, M) :- expr(M, L, []).

This works: calculate([+, 2, -, 9, 8], X]

but calculate([+, 2, [-, 9, 8]], X] gives false.

What do I need in order for it to work list inside of list?


回答1:


very simple:

...
expr(Z) --> [L], {calculate(L, Z)}.
calculate(L, M) :- expr(M, L, []).

yields

?- calculate([+,2,-,9,8],X).
X = 3 ;
false.

2 ?- calculate([+,2,[-,9,8]],X).
X = 3 ;
false.

btw calculate/3 should better be expressed with phrase/2 (at least in SWI-Prolog)

calculate(L, M) :- phrase(expr(M), L).

but an error arise on backtracking

?- calculate([+,2,[-,9,8]],X).
X = 3 ;
ERROR: Type error: `list' expected, found `8' (an integer)
   Exception: (14) expr(_G2432, [-, 9, 8], []) ? aabort
% Execution Aborted

then we need a guard:

calculate(L, M) :- is_list(L), phrase(expr(M), L).


来源:https://stackoverflow.com/questions/22740331/prolog-prefix-expression

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