Search code examples
listrecursionprologsublistvariable-length

Prolog Length of Evens in a List


I am a Prolog beginner, and I have the following length function:

mylen([H|Lc],N) :- mylen(Lc,M),N is M+1.
mylen([],0).

I would like to know if there's an easy way to query the interpreter to calculate the length of the list of evens in a list, and if not, how I would go about incrementing N only on an even number. Thanks.


Solution

  • Something similar to this is what you might be looking for

    mylen([H|Lc],N) :- 
    X is mod(H,2),
    X == 0,
    mylen(Lc,M),
    N is M+1.
    
    mylen([],0).
    
    mylen([H|Lc],N) :-
    mylen(Lc, M),
    N = M.