我已经写了一个程序,从递归表达式列表评估序言修复后的表达。 例如,假设下面的列表:
[+,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.
我不明白为什么我的价值观消失,或者是否有更好的方法来评估名单。