Home > Enterprise >  Uniting consecutive and equal elements in the array in Prolog
Uniting consecutive and equal elements in the array in Prolog

Time:06-02

Im traying to uniting consecutive and equal elements in the array in Prolog that if I call a list [1,1,1,a,b,b,3,3,3,3] The answer: [1,a,b,3]

CodePudding user response:

clumped/2 will turn them into pairs of the element and how often they repeat. Then remove the values from the pairs for the answer:

?- clumped([1,1,1,a,b,b,3,3,3,3], _Pairs),
   pairs_keys_values(_Pairs, Answer, _).

Answer = [1, a, b, 3]

CodePudding user response:

As DCG:

% For eos
:- use_module(library(dcg/basics)).

list_consecutives(Lst, LstCons) :-
    phrase(consec, Lst, LstCons),
    % First is correct
    !.

consec, [C] --> [C], consec_same(C), consec.
consec --> eos.

% Greedily consume a succession of the same element
consec_same(C) --> [C], consec_same(C).
consec_same(_) --> [].

Result in swi-prolog:

?- time(list_consecutives([1,1,1,a,b,b,3,3,3,3], L)).
% 24 inferences, 0.000 CPU in 0.000 seconds (88% CPU, 790175 Lips)
L = [1,a,b,3].
  • Related