该函数用于通过引用变量列表来评估任意结构化的表达式。 (我知道this question存在,但答案写得不好,我听不懂。)
我到目前为止的工作如下:
lookup(X, Env, V) :-
member(val(X,V),Env). //finds the value of a variable in the "environment".
eval(S, Env, V):-
lookup(S,Env,V). //if expression is a single variable name/key, return the value of the pair.
eval(H+T, Env, V):- //if expression is in the form of head+tail...
lookup(H,Env,HVal), //first, make sure that the head can be looked up;
eval(T, Env, V - HVal). //then, treat the tail as its own expression while expecting a modified value.
eval(F+S, Env, V):- //if expression is contains two atoms, evaluate their sum.
lookup(F, Env, FVal),
lookup(S, Env, SVal),
V is FVal + SVal.
... % minus, times etc. implemented similarly
现在,该代码可以很好地用于单值查找:
?- eval(a, [val(a,1),val(b,2),val(c,3)], V).
V = 1 .
以及“ diatomic”表达式:
?- eval(a+b, [val(a,1),val(b,2),val(c,3)], V).
V = 3 .
但不止如此(即a+b+a
)使代码立即返回false.
。
我的实现有什么问题?我该如何解决?