Prolog returns a list containing only elements that are equal to the head of the list

Hello, I would like to ask a doubt that I have the following code:

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

I would like to get a way:

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

X = [222,222,222]

But at this moment I only get the head:

X = [222]

So, to make this clear, I would like to: all consecutive occurrences of the first element in the list.

My doubt is what this assignment does P=[H|R], why not just put:

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

Also, how would you try to change this to get the result I asked for? Thanks you

+4
source share
2 answers

, . 1-, . 2-, , , .

1

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

... . , Prolog . library(diadem):

?- use_module(diadem).
   true.

?- principio([222,333,101,202,12,222,13,222],[222,222,222]).? Gen.
   Gen = principio([222, 333|_], [_, _|_])
;  Gen =  (dif(A100, B100), principio([A100, B100|_], [_, _|_]))
...

: , ! , — , !

?- dif(X, Y), principio([X,Y|_],[_,_|_]).

:- op(950, fy, *).
* _P_0.

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

. !

, , , principio([H,_|_],[H]).. - .

2nd

- :

?- principio([222,333,101,202,12,222,13,222],[222]).
true.         % incorrect !!

.

?- principio([222,222],[222]).
true.         % incorrect !!

, false, :

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

! . :

, , .

principio([],[]).
principio([H],[H]).
principio([H,D|Xs], [H|Hs]) :-
   dif(H,D),
   principio([H|Xs],[H|Hs]).
principio([H,H|Xs],[H|Hs]) :-
   principio([H|Xs],Hs).
+5

, @false (+ s (0)), DCG . (. ):

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

heads([],_H) -->          % in the empty list
   [].                    % there no element matching H
heads([H|Xs],H) -->       % if the head of the list matches H
   [H],                   % it 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 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
+2

Source: https://habr.com/ru/post/1676600/


All Articles