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.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
What you construct when you write
Sum+1is a term with functor'+'/2and argumentsSumand1.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
Xto the rest of the sum, not1:Using an accumulator would allow you to make the code tail-recursive…