使用序言替换两个列表之间的元素 [英] replacing elements between two lists using prolog
问题描述
我的任务是制作myReplace(E1,L1,E2,L2)
,以使L1
中最早出现的E1
替换为E2
,并在L2
中返回.我已经写了下面描述的代码,它可以正常工作.
My task is to make myReplace(E1,L1,E2,L2)
such that the very first occurrence of E1
in L1
gets replaced by E2
and is returned in L2
. I have written the below described code and it is working properly.
myReplace(E1,[],E2,[]).
myReplace(E1,[E1|Xs],E2,[E2|Ys]):-
myReplace(E1,Xs,E1,Ys).
myReplace(E1,[H|Hs],E2,[H|Ts]):-
E1 \= H,
myReplace(E1,Hs,E2,Ts).
但是,例如myReplace(2,[1,2,3,2,1],5,X)
应该给出X = [1,5,3,2,1]
和X = [1,2,3,5,1]
.但是我的代码只给出了一个解决方案,即X = [1,5,3,2,1]
.
However, For example myReplace(2,[1,2,3,2,1],5,X)
should give X = [1,5,3,2,1]
and X = [1,2,3,5,1]
. But my code is only giving one solution which is X = [1,5,3,2,1]
.
类似地,当myReplace(2,X,5,[1,5,3,5,1])
应该仅回溯解决方案X = [1,2,3,5,1]
和X = [1,5,3,2,1]
时,但是我的解决方案为我提供了另一个解决方案,如X = [1,5,3,5,1]
.
Similarly, when myReplace(2,X,5,[1,5,3,5,1])
should backtrack over the solutions X = [1,2,3,5,1]
and X = [1,5,3,2,1]
only, but my solution gives me one more solution as X = [1,5,3,5,1]
.
您能帮我解决这个问题吗?
Could you please help me resolve this.
谢谢:)
推荐答案
关于
myReplace(E1,[E1|Xs],E2,[E2|Xs]).
myReplace(E1,[H|Hs],E2,[H|Ts]):-
myReplace(E1,Hs,E2,Ts).
?
如果我没记错的话,这将强制进行一次(并且只有一次)替代.
If I'm not wrong, this impose one (and only one) replacement.
记入您必须删除的内容
myReplace(E1,[],E2,[]).
否则,您会得到L1 = L2
(无替代品)作为解决方案.
otherwise you get L1 = L2
(no replacement) as a solution.
并观察到,正如Lurker所指出的,这不是"L1中E1的第一次出现被替换".
And observe that, as pointed by Lurker, this isn't "the very first occurrence of E1 in L1 gets replaced".
这篇关于使用序言替换两个列表之间的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!