Please help me with how to count even numbers in a list in Prolog. I am a beginner, just started learning Prolog yesterday. I know to count the elements in the list is
mylen([H|Lc],N) :- mylen(Lc,M),N is M+1.
mylen([],0).
And I think defining even number maybe helpful in this case, and I guess the code is maybe something like:
even(n):-
N rem 2 =:= 0.
Can you help me with putting these two parts together, so my code counts even numbers? I know I also need to add a counter, but I have no idea of how to do this in Prolog.
Thank you so very much for you help!
If your Prolog system offers clpfd, you can use the meta-predicate
tcount/3
in combination witheven_truth/2
. Here's how:Both predicates (
tcount/3
andeven_truth/2
) are monotone and preserve logical-purity! This makes them very robust and enables you to always get logically sound answers.Consider the following more general query:
Currently, you have two rules:
(1) The number of elements in the empty list is
0
(2) The number of elements in the list
[H|Lc]
isN
if the number of elements in the listLc
isM
andN
isM+1
You're already armed with a predicate which is true if a number is even, and false if it is not:
N
is even if the remainder ofN
when divided by2
is0
:Now you can piece it together. The number of even elements in an empty list is still zero. So you keep rule (1). Your rule (2) will need to change as it will need to check if the head of the list is even. You can do this with with two rules in Prolog which take care of the two different cases (the list head is even, or the list head is odd):
(2a) The number of even elements in list
[H|Lc]
isN
ifH
is even, and the number of even elements in listLc
isM
, andN
isM+1
.(2b) The number of even elements in list
[H|Lc]
isN
ifH
is not even (orH
is odd), and the number of even elements in listLc
isN
. [Notice thatN
doesn't change ifH
is odd.]I'll leave the rendering of these two rules into Prolog as an exercise. You can use the Prolog negation functor,
\+
to test if a number is not even, by\+ even(N)
. Or you can define anodd(N) :- N rem 2 =:= 1.
predicate to use for that case.