【问题标题】:managing lists in prolog在 prolog 中管理列表
【发布时间】: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]]

但是仍然存在构建一个包含重复至少两次的不同元素的列表的问题。

如果有人可以帮助我或为我指明大方向,那就太好了。

提前致谢

【问题讨论】:

    标签: list prolog filtering


    【解决方案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

    【讨论】:

      【解决方案2】:

      你可以写一个程序:

      % 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).
      

      记得在完成后反转重复列表。

      【讨论】:

        猜你喜欢
        • 2021-02-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-22
        • 2014-05-21
        • 2013-06-19
        • 1970-01-01
        相关资源
        最近更新 更多