count successive occurrences of number in Prolog

后端 未结 5 570
情深已故
情深已故 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:41

    If we skip usage of "is" we can have a solution like:

    precondition(Clause):-
      Clause =.. [_|ARGS],
      ( maplist(var,ARGS) -> true; Clause ).
    
    count( [], [] ).
    
    count( [X], [(X,1)] ) :- !.
    
    count( [H|Q], [(H,1),(HR,NR)|QR] ) :-
       count( Q, [(HR,NR)|QR] ),
       H \= HR,
       !.
    
    count( [H|Q], [(H,NR)|QR] ) :-
       precondition( succ(N,NR) ),
       count( Q, [(H,N)|QR] ), 
       succ(N,NR).
    

    that allows not only the usual query:

    [debug]  ?- count([1,1,1,2,2,2,3,1,1],R).
    R = [ (1, 3), (2, 3), (3, 1), (1, 2)].
    

    but also the reverse one:

    [debug]  ?- count(X, [ (1, 3), (2, 3), (3, 1), (1, 2)] ).
    X = [1, 1, 1, 2, 2, 2, 3, 1, 1].
    

提交回复
热议问题