user236501
user236501

Reputation: 8648

Prolog sum all the number in the list.

How to sum all odd positioned elements in a list

example [1,2,3,4,5,6,7,8,9] = 25

odd([],0].
odd([Z],Z).
odd([X,Y|T], Sum+1):- odd(T,Sum).

but it return me 1+3+5+7+9.

Upvotes: 0

Views: 5869

Answers (4)

user1400451
user1400451

Reputation: 97

sum([],0).
sum([H|T],N) :-
       sum(T,M), N is H + M.

Upvotes: 0

salva
salva

Reputation: 10234

Get a list with the odd elements, then sum that list:

divide([], [], []).
divide([H|T], [H|L1], L2) :- divide(T, L2, L1).

sum(L, Sum) :- sum(L, 0, Sum).

sum([], Acu, Acu).
sum([H|T], Acu, Acu1) :-
  Acu2 is Acu + H,
  sum(T, Acu2, Acu1).

sum_odd(L, Sum) :-
  divide(L, Odds, _),
  sum(Odds, Sum).

:- sum_odd([1,2,5,6,8,9,1], Sum), writeln(Sum).

Upvotes: 0

twinterer
twinterer

Reputation: 2436

What you construct when you write Sum+1 is a term with functor '+'/2 and arguments Sum and 1.

In Prolog, when you want to calculate a sum, you need to use the predicate is/2.

In your code, you should also add cuts to remove unnecessary choicepoints, and add X to the rest of the sum, not 1:

odd([],0) :- !.
odd([Z],Z) :- !.
odd([X,_|T],Sum):- odd(T,Sum0), Sum is Sum0+X.

Using an accumulator would allow you to make the code tail-recursive...

Upvotes: 2

Stephan202
Stephan202

Reputation: 61469

In prolog you have to use the is operator when you want to evaluate arithmetic expressions. Since you use the + symbol outside of an arithmetic scope it is not interpreted specially. This appears to be homework, so I'll give a simplified example:

add(A, B, C) :- C is A + B.

The code above adds A and B and stores the result in C.

Upvotes: 3

Related Questions