Search code examples
prolog

How to find number of same elements in list Prolog?


I have a question about the topic,

I know the list of Prolog works like [head, (tail)] but is there any function or magical touch(sample codes) to find number of elements in the list?. Is there any way to get number of same elements in the list then compare the list or the unique element in it?


Solution

  • One way is as follows:

    get_uniq(List,Uniq) :-
        select(Uniq,List,SubList),   % chose an item from the list
        \+ member(Uniq,SubList).     % make sure it doesn't have a pair
    

    %% added later

    You can get full list of unique items with:

    findall(N,get_uniq([2,1,4,3,2,5,1,4,3],N), Ns).