我正在尝试从列表中删除重复项,同时保留最右边的出现次数。例如:
[1,2,3,1,2]
转换为 [3,1,2]
。这是我在 Prolog 中的第一次尝试,我不明白我做错了什么。它总是返回 false。这是我的代码:%nrap(L:list,E:element,S:integer)
%L - the initial list, list of integers
%E - the element, integer
%S - the result, nrap of E in L, S integer
%flow model: (i,i,o),(i,i,i)
nrap([],_,0).
nrap([H|T],E,S):-
H=E,
nrap(T,E,S1),
S is S1+1.
nrap([H|T],E,S):-
H\=E,
nrap(T,E,S).
%transform(L:list,L2:list,R:list)
%L - the initial list, list of integers
%L2 - copy of the initial list
%R - the resulted list, without duplicates, list of integers
%flow model: (i,i,o),(i,i,i)
transform([],[],[]).
transform([H|T],L2,[H|R]):-
nrap(L2,H,S),
S=1,
transform(T,L2,R).
transform([H|T],L2,R):-
nrap(L2,H,S),
S>1,
transform(T,L2,R).
transform/3
失败是因为第二个参数L2
从未被“驱动”到空列表[]
,而你的基本情况假设了这一点。L2
永远不会改变。尝试将transform([],_,[])
作为你的基本情况。 - lurkerL2
。你在递归过程中一直使用相同的L2
。由于你正在计算L2
中的元素数量,因此元素数量S
在整个过程中永远不会改变。这将无法成功处理S = 1
的情况。 - lurker