Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.3k views
in Technique[技术] by (71.8m points)

list - Sum of even, product of odd numbers in Prolog

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).
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here is a suggestion for the sum of the even numbers from a list:

even(X) :- 
  Y is mod(X,2),       % using "is" to evaluate to number
  Y =:= 0.

odd(X) :-              % using even
  Y is X + 1,
  even(Y).

sum_even(0, []).       % empty list has zero sum
sum_even(X, [H|T]) :- 
  even(H),
  sum_even(Y, T), 
  X is Y+H.
sum_even(X, [H|T]) :- 
  odd(H),
  sum_even(X, T).      % ignore the odd numbers

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:

| ?- sum_even(X,[]).    
X = 0 ?     
yes

| ?- sum_even(X,[2]).   
X = 2 ? 
yes

| ?- sum_even(X,[3]).    
X = 0 ? 
yes

| ?- sum_even(X,[5,4,3,2,1,0]).    
X = 6 ? 
yes

The ideas applied here should enable you to come up with the needed product.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...