2011-11-21 26 views
0

我是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]] 

以下列表中出现,但仍然存在建立一个列表的问题将包含重复至少两次的不同元素。

如果任何人都可以帮助我,或者指出我的大方向。

在此先感谢

回答

0

你可以写一个程序:

% E it's the list of are elements from L that repeat at least twice 
elements_that_repeat_at_least_twice(L, E) :- 
    elements_that_repeat_at_least_twice(L, [], E). 

elements_that_repeat_at_least_twice([H|Ls], Dupl, E) :- 
    ... 

在elements_that_repeat_at_least_twice添加列表DUPL将保持每个元素您验证它是否出现多次。使用[H | Ls]检查L的每个元素。 使用memberchk/2验证H是否在L中:那么它至少是重复的。如果它还没有在Dupl中,添加到它,并递归。请记住写出递归基例(停在空列表[]处)。

现在,我看到您已经添加一些代码:然后我完整的建议:

elements_that_repeat_at_least_twice([], Dupl, Dupl). 
elements_that_repeat_at_least_twice([H|Ls], Dupl, E) :- 
    ( memberchk(H, Ls) 
    -> (\+ memberchk(H, Dupl) 
    -> Dupl1 = [H|Dupl] 
    ; Dupl1 = Dupl 
    ) 
    ; Dupl1 = Dupl 
), 
    elements_that_repeat_at_least_twice(Ls, Dupl1, E). 

记住扭转重复的列表完成时。

1
an element E of list L should: 
    be a member of list L', 
    be a member of list L'' where L'' is list L' if we remove element E. 

检查select/3member/2findall/3和/或setof/3