【发布时间】:2011-11-22 06:27:44
【问题描述】:
我是 Prolog 的新手,正在寻求帮助。我想要做的基本上是得到一个列表 L,其中包含在给定列表 L'中至少重复两次的元素'
示例 L'=[1,2,1,3,4,3,2] => L=[1,2,3]。
到目前为止,我能够计算每个连续变量的出现次数
% pack(L1,L2) :- the list L2 is obtained from the list L1 by packing
% repeated occurrences of elements into separate sublists.
% (list,list) (+,?)
pack([],[]).
pack([X|Xs],[Z|Zs]) :- transfer(X,Xs,Ys,Z), pack(Ys,Zs).
% transfer(X,Xs,Ys,Z) Ys is the list that remains from the list Xs
% when all leading copies of X are removed and transfered to Z
transfer(X,[],[],[X]).
transfer(X,[Y|Ys],[Y|Ys],[X]) :- X \= Y.
transfer(X,[X|Xs],Ys,[X|Zs]) :- transfer(X,Xs,Ys,Zs).
% encode(L1,L2) :- the list L2 is obtained from the list L1 by run-length
% encoding. Consecutive duplicates of elements are encoded as terms [N,E],
% where N is the number of duplicates of the element E.
% (list,list) (+,?)
encode(L1,L2) :- pack(L1,L), transform(L,L2).
transform([],[]).
transform([[X|Xs]|Ys],[[N,X]|Zs]) :- length([X|Xs],N), transform(Ys,Zs).
这将返回以下 touples 列表
?- encode([a,a,a,a,b,c,c,a,a,d,e,e,e,e],X).
X = [[4,a],[1,b],[2,c],[2,a],[1,d][4,e]]
但是仍然存在构建一个包含重复至少两次的不同元素的列表的问题。
如果有人可以帮助我或为我指明大方向,那就太好了。
提前致谢
【问题讨论】: