Search code examples
listprolog

Prolog: Count number of times e appears in a list in odd positions


I can't figure out why this is constantly returning false. I can count the number of element "e" in a list in odd positions if I call another function, but I want to do it in a more clean and compact way. Here is the code:

count(_,[],0).
count(E,[E,_|T],C) :-
    count(E,T,D),
    C is D+1.
count(E,[H,_|T],C) :-
    E\=H,
    count(E,T,C).

Solution

  • Your current formulation is correct when the list has even number of elements:

    ?- count(x, [x, y, x, x], C).
    C = 2 
    

    But it will fail if the number of elements is odd.

    To correct this you can just add couple of rules for one-element lists:

    count(E,[E],1).
    count(E,[H], 0):-
        E\=H.
    

    Now it works for lists with odd number of elements:

    ?- count(x, [x, y, x, x, x], C).
    C = 3 
    
    ?- count(y, [x, y, x, x, x], C).
    C = 0 
    
    ?- count(x, [y, y, y, y, x], C).
    C = 1