Prolog suma todos los números de la lista.

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.

preguntado el 09 de noviembre de 11 a las 11:11

4 Respuestas

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` y los `B` y almacena el resultado en `C`.

respondido 09 nov., 11:16

odd([],0]. odd([Z],Z). odd([X,Y|T], Sum):- Sum1 is Sum + X, odd(T,Sum1 ). Is this correct but I got error will run the program. - user236501

What you construct when you write `Sum+1` is a term with functor `'+'/2` y argumentos `Sum` y los `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...

respondido 09 nov., 11:19

I got false return with your method. Thanks - user236501

Olvidé el `Sum` parameter in the third clause. Thanks for notifying me. I edited the answer. - twinterer

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

respondido 11 nov., 11:13

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

contestado el 28 de mayo de 12 a las 06:05

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.