我编写了一个程序来从表达式列表递归地评估 prolog 中的后修复表达式。例如,给定以下列表:
[+,1,2]
它应该返回 3。我构建谓词的方式是递归调用自身,直到它到达列表的末尾,以便它向后读取值。(与从左到右阅读此列表相同:[2,1,+])。
我的问题是,当我尝试通过递归调用返回多个值时,所有值都会突然消失。
这是代码:
eval_list([Head|Tail],_,Result):-
Tail==[], % last element of list
Result=Head,
write(Head),
write(' was stored in Result!\n').
eval_list([Head|Tail],Store1,Result):-
eval_list(Tail,Store2, NewResult),
(\+integer(Store2))
->
% if no integer is bound to Store2, bind Store1 to Head
Store1=Head,
Result is NewResult,
write(Head),
write(' is stored value!\n')
; (integer(Store2)) ->
% if an integer is bound to store2, we perform operation specified by the Head with the stored number
X is Store2+NewResult,
Result is X,
write('performed operation!\n')
;
% if doesnt catch either of these states the program is broken
( print('something broke\n'),
print(Store1),
nl,
print(Store2),
nl,
print(Head),
nl,
print(Result),
nl
).
我得到以下输出:
?- eval_list([+,1,2],X,Result).
2 was stored in Result!
1 is stored value!
something broke
_G1162
_L147
+
_G1163
true.
我不明白为什么我的价值观会消失,或者是否有更好的方法来评估列表。