Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.5k 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...