Hi guys, any solution to this problem - given a list of numbers [1,2,3,4,5] write a Prolog program to sum up all the odd-positioned in this list ?
odd([1,2,3,4,5],Sum)
Sum = 9. (1+3+5)
Hi guys, any solution to this problem - given a list of numbers [1,2,3,4,5] write a Prolog program to sum up all the odd-positioned in this list ?
odd([1,2,3,4,5],Sum)
Sum = 9. (1+3+5)
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.
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. ;-)