count successive occurrences of number in Prolog

后端 未结 5 621
情深已故
情深已故 2021-01-23 05:57

Hello I am trying to make a program in Prolog that given a list it counts the occurrences of each successive element in the list as follows:

count(1,[1,1,1,2,2,2         


        
5条回答
  •  天命终不由人
    2021-01-23 06:53

    Another solution (tail recursive) is this:

    run_length_encode( Xs , Ys ) :- % to find the run length encoding of a list ,
      rle( Xs , 1 , Ys ) .          % - just invoke the helper
    
    rle( []       , _ , []    ) .     % the run length encoding of the empty list is the empty list
    rle( [A]      , N , [X:N] ) .     % A list of length 1 terminates the run: move the run length to the result
    rle( [A,A|Xs] , N , Ys    ) :-    % otherwise, if the run is still going
      N1 is N+1 ,                     % - increment the count, 
      rle( [A|Xs] , N1 , Ys )         % - and recurse down
      .                               %
    rle( [A,B|Xs] , N , [A:N|Ys] ) :- % otherwise, if the run has ended
      A \= B ,                        % - we have a break
      rle( [B|Xs] , 1 , Ys )          % - add the completed run length to the result and recurse down
      .                               %
    

提交回复
热议问题