count successive occurrences of number in Prolog

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

    Why you are stating a relation between two lists with a predicate having 4 arguments ? Let's try to proceed step by step.

    An empty list gives an empty list, an element counted gets incremented, otherwise, start counting...

    count([],[]).
    count([X|T],[[X,C1]|R]) :- count(T,[[X,C]|R]), !, C1 is C+1.
    count([X|T],[[X,1]|R]) :- count(T,R).
    
    ?- count([1,1,1,2,2,2,3,1,1],R).
    R = [[1, 3], [2, 3], [3, 1], [1, 2]].
    

    so easy (of course, assuming X=[ [1,3],[2,3],[1,3][1,2] ] it's a typo ...)

提交回复
热议问题