Search code examples
lispcommon-lisp

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

Solution

  • 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.