Prolog前缀表达式
问题描述:
我可以从前缀表达式获得总和,但是只要在列表中添加一个列表,程序就不会运行。
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, []).
这样做: calculate([+,2, - ,9,8 ],X]
但计算([+,2,[ - ,9,8]],X ]
给出了错误。
为了让列表中的列表工作,我需要什么?
What do I need in order for it to work list inside of list?
答
非常简单:
...
expr(Z) --> [L], {calculate(L, Z)}.
calculate(L, M) :- expr(M, L, []).
收益率
?- 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).
但回溯出现错误
?- 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).