Prolog gets list frequency

Work with the prologue.

I have a structure cnt(letter,number).

I need to return a list cntwhere each cntis the number of times each character appears (provided that each element has already been sorted to place the same element one by one).

I still have this:

cnt(letter,number).

freq([],[]).

freq([A|L],Y) :- grab(A,Init,_), freq(L,[Init|Y]).

The grab function correctly takes a list of elements and returns a list of the first duplicates as Init

eg grab([a,a,a,b,c], Init, Rest).will return Init = [a,a,a].

Assuming I have a list [a,a,a,b,b,b,c,c]I need freq to returnY = [cnt(a,3), cnt(b,3), cnt(c,2)].

I think I'm still close to the rule, except that it returns false.

Is there a way to get through to see what he does to get there? Or someone might see any obvious problems.

+4
3

, , .

freq([],[]).
freq([A|L],Y) :- grab(A,Init,_), freq(L,[Init|Y]).

freq/2 - . , :

freq([],_).
freq([A|L],_) :- ..., freq(L,_).

, ? , . , [a,a], , freq/2 , .

. , :

freq(_,[]).
freq(_,Y) :- ..., freq(_,[Init|Y]).

, freq(_,[Init|Y]), . - , ? freq(_,[]). , - , . , freq(_,[Init|Y]) . , Init Y.

, :

freq([],[]).
freq([A|L],[As|Y]) :-
   grab([A|L],As,K),
   freq(K,Y).

:

?- freq([a,a,a,b,b,b,c,c],Ys).
Ys = [[a,a,a],[b,b],[c,c]].

, , cnt(a,3) .

freq([],[]).
freq([A|L],[cnt(A,N)|Y]) :-
   grab([A|L],As,K),
   length(As, N),
   freq(K,Y).
+7

, ( ).

freq ([], []) , ,

freq([], [cnt(0, _)])

.

:

freq([A], [cnt(1,A)]).

, Prolog , , :

freq([A | T], R) :-
    freq(T, R1),
    process(A, R1, R).

, R1, : R1 = [cnt (V, A) | L] R1 = [cnt (V, B) | L] A, B.

,

process(A, [cnt(V, A)|L], [cnt(V1, A) | L]) :-
    V1 is V+1.

process(A, [cnt(V, B)|L], [cnt(1, A), cnt(V, B) | L]) :-
    A \= B.
+3

I would think so (assuming the list is already ordered)

frequency( []     , [] ) .   % the frequency table for the empty list is the empty list
frequency( [X|Xs] , F  ) :-  % for a non-empty list,
  tabulate( Xs , X:1 , F )   %   we just invoke the tabulation predicate, seeding the accumulator with the initial count.
  .                          %

tabulate( []     , C:N , [C:N] ) .    % if the source list is exhausted, we're done: shift the accumulator to the result list.
tabulate( [X|Xs] , X:N , F ) :-       % otherwise, 
  ! ,                                 % - and we haven't yet hit a sequence break,
  N1 is N+1 ,                         % - increment the frequency
  tabulate( Xs , X:N1 , F )           % - and recurse down.
  .                                   %
tabulate( [X|Xs] , C:N , [C:N|F] ) :- % finally, if we have a sequency break: shift the accumulator to the result list
  tabulate( Xs , X:1 , F )            % and recurse down
  .                                   %

Sorts the list, and then makes a single pass through the list, counting when we go.

0
source

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


All Articles