序言替换 [英] Prolog substitution
问题描述
如何用另一个包含要替换的变量的列表替换一个列表.例如
How can I replace a list with another list that contain the variable to be replaced. for example
rep([x, d, e, z, x, z, p], [x=z, z=x, d=c], R).
R = [z, c, e, x, z, x, p]
x 到 z 和 z 被替换后不会改变.
the x to z and z doesn't change after it has been replaced.
到目前为止我只做了一个没有列表的
so far I did only the one without the list
rep([], _, []).
rep(L1, H1=H2, L2) :-
rep(L1, H1, H2, L2).
rep([],_,_,[]).
rep([H|T], X1, X2, [X2|L]) :-
H=X1,
rep(T,X1,X2,L),
!.
rep([H|T],X1,X2,[H|L]) :-
rep(T,X1,X2,L).
推荐答案
我发现您的代码相当混乱.一方面,您有 rep/3
和 rep/4
,但它们都没有在您传递变量绑定列表的第二个位置有列表.H1=H2
不可能匹配一个列表,这是唯一一个检查第二个参数的 rep/3
子句.如果这是课堂作业,看起来你有点落后,我建议你花一些时间在之前的材料上.
I find your code rather confused. For one thing, you have rep/3
and rep/4
, but none of them have a list in the second position where you're passing the list of variable bindings. H1=H2
cannot possibly match a list, and that's the only rep/3
clause that examines the second argument. If this is a class assignment, it looks like you're a little bit behind and I'd suggest you spend some time on the previous material.
解决方案比您想象的要简单:
The solution is simpler than you'd think:
rep([], _, []).
rep([X|Xs], Vars, [Y|Rest]) :- member(X=Y, Vars), rep(Xs, Vars, Rest).
rep([X|Xs], Vars, [X|Rest]) :- \+ member(X=_, Vars), rep(Xs, Vars, Rest).
我们使用 member/2
在列表中查找变量绑定"(用引号引起来,因为它们是原子而不是真正的 Prolog 变量).如果它在列表中,则 Y 是替代品,否则我们继续使用 X.您会看到这具有预期的效果:
We're using member/2
to find a "variable binding" in the list (in quotes because these are atoms and not true Prolog variables). If it's in the list, Y is the replacement, otherwise we keep using X. And you see this has the desired effect:
?- rep([x, d, e, z, x, z, p], [x=z, z=x, d=c], R).
R = [z, c, e, x, z, x, p] ;
false.
直接使用或"可以提高效率(并为我们节省一个选择点):
This could be made somewhat more efficient using "or" directly (and save us a choice point):
rep([], _, []).
rep([X|Xs], Vars, [Y|Ys]) :-
(member(X=Y, Vars), ! ; X=Y),
rep(Xs, Vars, Ys).
见:
?- rep([x, d, e, z, x, z, p], [x=z, z=x, d=c], R).
R = [z, c, e, x, z, x, p].
这篇关于序言替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!