Prolog - Sum up "positioned" elem in list
I am looking for a solution to the following problem开发者_开发百科: "Write a Prolog program to sum up all the odd-positioned in a given list."
Sample query:
?- odd([1,2,3,4,5],Sum).
Sum = 9. % correct as 1+3+5 equals 9
Direct implementation:
odd([],0).
odd([X|Xs],S) :- even(Xs,S0), S is S0+X.
even([],0).
even([_|Xs],S) :- odd(Xs,S).
Sample queries:
?- odd([],S).
S = 0.
?- odd([1],S).
S = 1.
?- odd([1,_],S).
S = 1.
?- odd([1,_,3],S).
S = 4.
?- odd([1,_,3,_],S).
S = 4.
?- odd([1,_,3,_,5],S).
S = 9.
The sum of 'odd-positioned' elements can be found by the following; where lists are indexed from 0:
odd_sum_nth0([_,X|Y], Sum) :-
odd_sum_aux(Y, X, Sum).
Else, were lists are indexed from 1:
odd_sum_nth1([X|Y], Sum) :-
odd_sum_aux(Y, X, Sum).
Given:
odd_sum_aux([_, W|X], Y, Sum) :-
!, Z is W + Y,
odd_sum_aux(X, Z, Sum).
odd_sum_aux(_, Sum, Sum).
Caveat emptor. ;-)
This looks like homework, so I'll just give you a nudge in the right direction. The problem is really two separate problems: filter and sum. Solve these separately, and implement odd by composing the solutions.
精彩评论