【问题标题】:How to find a common element in two lists? Prolog如何在两个列表中找到共同的元素?序言
【发布时间】:2020-11-14 04:38:57
【问题描述】:

假设我有两个列表 [1,2,3,4] 和 [2,4,5,1]。这两个列表中的共同元素是[1,2]。

这个问题有一个简单的方法:

common_element(L1,L2) :- member(E,L1), member(E,L2).

但我正在尝试编写自己的谓词:

common_element([],[]).   
common_element([H1|T1],[H2|T2]):-
        (   H1=H2-> writeln(H1),
        common_element(T1,[H2|T2]);  
        common_element([H1|T1],T2)).

但它不起作用。它只检查第一个公共元素。

?- common_element([1,2,66,6],[5,6,3,1]).
1

它应该返回 1,6。

【问题讨论】:

  • 你的问题是什么?
  • Q.如何在两个列表中找到共同的元素? Prolog 我首先写了这个问题,然后最终能够自己解决它,所以我后来添加了解决方案。 :)
  • 太好了,你正在学习!您应该删除解决方案并将其写在您(自己的)问题的答案中!

标签: prolog


【解决方案1】:

根据 Reema 的回答,这里有一个更“有用”的谓词“返回”公共元素,而不是仅仅将它们写出来并最终失败。

%common_element(L1, L2, CommonElements_Of_L1_and_L2)
common_element([], _, []).
common_element([H|T], L2, [H|L1]):- member(H, L2), !, common_element(T, L2, L1).
common_element([_|T], L2,    L1):-  common_element(T, L2, L1).

例子

?- common_element([1,2,66,6], [5,6,3,1], L).
L = [1,6]

【讨论】:

    【解决方案2】:

    所以我在查看 peter.cyc 答案后更新我的解决方案:

    common_element([],_,[]).
    common_element([H|T],[H2|T2],[H|L]):-
        (   member(H,[H2|T2])-> !,common_element(T,[H2|T2],L);
        common_element(T,[H2|T2],L)).
    
    ?-common_element([1,2,66,6],[5,6,3,1],P).
      P = [1,6]
      
    

    【讨论】:

      猜你喜欢
      • 2016-07-06
      • 1970-01-01
      • 1970-01-01
      • 2011-08-22
      • 1970-01-01
      • 2021-01-01
      • 1970-01-01
      • 2015-12-16
      • 1970-01-01
      相关资源
      最近更新 更多