我在Prolog中很难理解"树"遍历的概念。
给定一个输入列表,下面的代码将替换叶中存在的原子hi到bye(忽略函子(。我把评论%放在让我困惑的部分旁边:
replace([],[]).
replace([H | T], [H1 | T1]):-
( H == hi -> H1 = bye;
replace(H, H1) % P1: What exactly does replace (H,H1) do? I know that
% is saying if H = hi then H1 = bye; else ..
),
replace(T, T1).
% The rule below is called in the replace(H,H1) above as well as the replace(T,T1).
% I am unsure as to what exactly this does.
replace(L, R):-
L =.. [F1 | Args1],
replace(Args1, Args2),
R =.. [F1 | Args2].
上面的代码输出:
?- replace(put(hi,table,aside(hi(dont,replace),hi)),X).
X = put(bye, table, aside(hi(dont, replace), bye))
我将感谢所有的帮助。提前谢谢。
replace/2的第二个子句应用运算符=。。(由于历史原因被调用univ(以获得术语的不同表示,如列表[Functor|Arguments]
,然后尝试替换此类Arguments,并最终重新组装术语,始终通过univ.
如果您也想替换函子,只需简化子句:
replace(L, R):-
L =.. In,
replace(In, Out),
R =.. Out.
由于Prolog有一个关系数据模型,有时输入/输出的区别并没有帮助,而且它只是一个命名约定。重要的是参数的实例化模式。内置谓词(univ是一个例子(通常试图提供最灵活的模型,也就是说,它们可以向后工作,但这一特性并不总是可行的。
对于这个片段,In/Out清楚地传达了。。。