Martina
Martina

Reputation: 53

Sum of odd elements in lisp

I have to sum odd elementс that are on odd positions. This is not working. Can someone tell me where is my mistake? Thank you

(defun sum (list)
  (cond
    ((null list) 0)
    ((= (mod 2 (car list)) 0) (sum (cddr list)))
    (T (+ (car list) (sum (cddr list))))))

Upvotes: 0

Views: 949

Answers (2)

Leo
Leo

Reputation: 1934

Check the order of the arguments of the function mod. It should be:

(= (mod (car list) 2) 0)

To avoid this mistake, you can use the function evenp instead.

Upvotes: 4

Joshua Taylor
Joshua Taylor

Reputation: 85823

Your original definition (sum odd elements at odd positions) actually translates into a loop very cleanly:

(loop for i from 0 
  for x in '(0 1 2 3 4 5 6)
  when (and (oddp i) (oddp x))
  sum x)

Your original solution moved down the list by cddr, which is actually a pretty nice way to do this. You can do it with loop as well (the initial call to rest is just to get things started at index 1):

(loop for x in (rest '(0 1 2 3 4 5 6)) by #'cddr
   when (oddp x)
   sum x)

Upvotes: 6

Related Questions