I have a list of numbers, I need to calculate the sum of the even numbers of the list and the product of the odd numbers of the same list. I'm new in Prolog, and my searches so far weren't successful. Can anyone help me solve it ?
l_odd_even([]).
l_odd_even([H|T], Odd, [H|Etail]) :-
H rem 2 =:=0,
split(T, Odd, Etail).
l_odd_even([H|T], [H|Otail], Even) :-
H rem 2 =:=1,
split(T, Otail, Even).
Use clpfd!
Building on meta-predicate
foldl/4
, we only need to define what a single folding step is:Let's fold
sumprod_/3
over the list!Sample query:
Alternatively, we can define
sumprod_/3
even more concisely by usingif_/3
andzeven_t/3
:Here is a suggestion for the sum of the even numbers from a list:
Note: My Prolog has oxidized, so there might be better solutions. :-)
Note: Holy cow! There seems to be no Prolog support for syntax highlighting (see here), so I used Erlang syntax. Ha, it really works. :-)
Running some queries in GNU Prolog, I get:
The ideas applied here should enable you to come up with the needed product.
It shouldn't get much simpler than
untested!