Prolog返回一个列表,其中只包含与列表头部相等的元素

时间:2017-05-07 14:56:21

标签: prolog

你好,我想用以下代码来质疑:

principio([],[]).
principio([H],[H]).
principio([H,_|_],[H]).
principio([H,H|C],P) :-
    principio([H|C],R),P=[H|R].

我想要一种方法:

?- principio([222,333,101,202,12,222,13,222],X).

X = [222,222,222]

但是在这一刻我只得到了头脑:

X = [222]

所以,为了清楚起见,我希望: 第一个元素的所有连续出现 作为列表。

我怀疑这项任务是什么P=[H|R]为什么不放弃:

principio([H,H|C],P) :-
    principio([H|C],P)

另外,你会如何修改它以获得我要求的结果? 谢谢

1 个答案:

答案 0 :(得分:3)

除了@false(+ s(0))提供的非常好的答案之外,我还要指出使用DCG进行任务的可能性。在描述列表时,它们通常会产生易于阅读的代码(请参阅语法规则旁边的注释):

principio([H|T],Hs) :-
   phrase(heads([H|T],H),Hs).

heads([],_H) -->          % in the empty list
   [].                    % there's no element matching H
heads([H|Xs],H) -->       % if the head of the list matches H
   [H],                   % it's in the list
   heads(Xs,H).           % same for the tail
heads([X|Xs],H) -->       % if the head of the list is
   {dif(X,H)},            % different from H it's not in the list
   heads(Xs,H).           % same for the tail

因此,您的示例查询会产生所需的结果:

   ?- principio([222,333,101,202,12,222,13,222],X).
X = [222,222,222] ? ;
no