Prolog 序言:更新列表的元素
我有一个“sn(N,C,p)”格式的新元素列表,一个旧列表和一个新列表。我正在尝试写更新(NewElements,OldList,NewList),如果新的C小于旧的C,那么OldList中的每个sn(N,u,u)都会更新它 以下是一个例子: 更新([sn(b,5,b),sn(a,1,a)],[sn(a,2,a),sn(b,4,b)],[sn(a,1,a),sn(b,4,b)]) -|对 我已经尝试过这些代码,但它只在只有一个新元素时起作用:Prolog 序言:更新列表的元素,prolog,Prolog,我有一个“sn(N,C,p)”格式的新元素列表,一个旧列表和一个新列表。我正在尝试写更新(NewElements,OldList,NewList),如果新的C小于旧的C,那么OldList中的每个sn(N,u,u)都会更新它 以下是一个例子: 更新([sn(b,5,b),sn(a,1,a)],[sn(a,2,a),sn(b,4,b)],[sn(a,1,a),sn(b,4,b)]) -|对 我已经尝试过这些代码,但它只在只有一个新元素时起作用: same(X,X). update_helper(
same(X,X).
update_helper(_, [ ], [ ]).
update_helper(sn(N1,C1,P1), [sn(N2,C2,P2)|T1], [sn(N3,C3,P3)|T2]) :-
\+N1 == N2,
same(sn(N2,C2,P2),sn(N3,C3,P3)),
update_helper(sn(N1,C1,P1), T1, T2).
update_helper(sn(N1,C1,P1), [sn(N2,C2,P2)|T1], [sn(N3,C3,P3)|T2]) :-
N1 == N2,
C1 < C2,
same(sn(N1,C1,P1),sn(N3,C3,P3)),
update_helper(sn(N1,C1,P1), T1, T2).
update_helper(sn(N1,C1,P1), [sn(N2,C2,P2)|T1], [sn(N3,C3,P3)|T2]) :-
N1 == N2,
C1 >= C2,
same(sn(N2,C2,P2),sn(N3,C3,P3)),
update_helper(sn(N1,C1,P1), T1, T2).
update([ ], _, _).
update([H|T], Old, New) :-
update(T, Old, New),
update_helper(H, Old, New).
相同(X,X)。
更新\u帮助程序(\u、[]、[])。
更新(sn(N1,C1,P1),[sn(N2,C2,P2)| T1],[sn(N3,C3,P3)| T2]):-
\+N1==N2,
相同(sn(N2,C2,P2),sn(N3,C3,P3)),
更新_助手(sn(N1,C1,P1),T1,T2)。
更新(sn(N1,C1,P1),[sn(N2,C2,P2)| T1],[sn(N3,C3,P3)| T2]):-
N1==N2,
C1=C2,
相同(sn(N2,C2,P2),sn(N3,C3,P3)),
更新_助手(sn(N1,C1,P1),T1,T2)。
更新([],u,u)。
更新([H | T],旧,新):-
更新(T、旧、新),
更新辅助对象(H、旧、新)。
我想你可以这样做:
update([], Old, Old).
update([X|Xs], Old, New) :-
update_helper(X, Old, Lst), % Old is updated as Lst
update(Xs, Lst, New). % Lst is updated as New
update_helper(_, [], []).
update_helper(sn(N,C1,P1), [sn(N,C2,_)|Old], [sn(N,C1,P1)|Old]) :-
C1<C2.
update_helper(sn(N1,C1,_), [sn(N2,C2,P2)|Old], [sn(N2,C2,P2)|New]) :-
once(N1 \= N2 ; C1 >= C2),
update_helper(sn(N2,C2,P2), Old, New).
我想你可以这样做:
update([], Old, Old).
update([X|Xs], Old, New) :-
update_helper(X, Old, Lst), % Old is updated as Lst
update(Xs, Lst, New). % Lst is updated as New
update_helper(_, [], []).
update_helper(sn(N,C1,P1), [sn(N,C2,_)|Old], [sn(N,C1,P1)|Old]) :-
C1<C2.
update_helper(sn(N1,C1,_), [sn(N2,C2,P2)|Old], [sn(N2,C2,P2)|New]) :-
once(N1 \= N2 ; C1 >= C2),
update_helper(sn(N2,C2,P2), Old, New).
另一种可能的解决方案,使用:
另一种可能的解决方案,使用:
你知道吗?我不知道,因为我刚开始学习prolog,这是一个简单的练习,但感谢你的帮助。你知道吗?我不知道,因为我刚开始学习prolog,这是一个简单的练习,但感谢你的帮助。有关更多要点,请尝试使用来自的谓词添加答案。我的快速猜测是使用maplist/3@GuyCoder完成!谢谢你的建议!要了解更多信息,请尝试使用来自的谓词添加答案。我的快速猜测是使用maplist/3@GuyCoder完成!谢谢你的建议!
update(NewElements, Old, New) :-
maplist(updated(NewElements), Old, New).
updated(NewElements, sn(N2,C2,P2), Updated) :-
( ( member(sn(N1,C1,P1), NewElements),
N1 = N2,
C1 < C2 )
-> Updated = sn(N1,C1,P1)
; Updated = sn(N2,C2,P2) ).
?- update([sn(b,5,b), sn(a,1,a)], [sn(a,2,a), sn(b,4,b)], L).
L = [sn(a, 1, a), sn(b, 4, b)].