how to count odd and even number with using PROLOG
question is:
when we key in mem([1,2,3,4,5]).
we will get the output as bellow:
odd=3
even=2
my coding i开发者_开发问答s like that but cannot run. can help me check where is my mistake??
mem(X,[X|L]).
mem(X,[element|L]):- mem([X,L]).
count([],L,L).
count([X|H],L1,L2):- write(even), X%2=0,nl, write(odd), X%2>=1,nl, count([H],[X|L1],L2).
thanks for your helping.
The procedures you have written do two different things and don't actually belong together. mem/2
is equivalent to the usually builtin member/2
except that your definition contains an error: in the second clause element
is an atom instead of a variable so it will not match other elements of the list. The usual definition is
member(X, [X|_]).
member(X, [_|L]) :- member(X, L).
Note that this definition will not only test if a term is an element of a list but can even be use to generate a list.
What exactly are you trying to do in count/3
: split the list into two lists, one containing odd and the other containing even; or count the number of odd and even elements? The splitting could be done with something like:
count([], [], []).
count([X|L], O, E) :- X rem 2 =/= 0, count(L, [X|O], E).
count([X|L], O, E) :- X rem 2 =:= 0, count(L, O, [X|E]).
Note that =/= /2
and =:= / 2
force evaluation of arguments as arithmetic expressions while = /2
attempts to unify its arguments.
Counting the number of odds and evens can be done in a similar fashion, and is left as an exercise for the reader. :-)
精彩评论