1

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
repeat
  • 18,496
  • 4
  • 54
  • 166
wOOt
  • 19
  • 1

3 Answers3

1

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.
repeat
  • 18,496
  • 4
  • 54
  • 166
0

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. ;-)

  • Nor [this](https://stackoverflow.com/questions/4373207/filter-list-prolog/4374962#comment48159961_4374962), nor [that](https://stackoverflow.com/questions/26329754/finding-the-longest-contiguous-sublist-in-prolog/26353452#comment48159933_26353452). – false Jan 01 '20 at 12:41
  • While using a cut, this solution produces clean errors for insufficiently instantiated partial lists. – false Jan 02 '20 at 17:03
  • ?!? not clear to me what you mean. I discovered your messages (that have been deleted in the meantime) where you talked to me directly and claimed I would downvote you. – false Jan 15 '20 at 11:45
-1

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.

Marcelo Cantos
  • 181,030
  • 38
  • 327
  • 365