I'd like to find elisp's analog of:
sum(n for n in numbers if n % 2) # Python
numbers.select { |n| n % 2 != 0 }.inject { |a, b| a + b } # Ruby
Imperative way:
(defun oddp (number)
(not (= (mod number 2) 0)))
(defun sum-odd-with-dolist (list)
(let ((acc 0))
(dolist (item list acc)
(if (oddp item)
(setq acc (+ item acc))))))
From Porting Common Lisp:
(defun sum-odd-with-dolist-incr (list)
(let ((total 0))
(dolist (item list)
(if (oddp item)
(incf total item)))
total))
Using 'cl-*
' loop
:
(defun sum-odd-with-loop (list)
(loop for x in list if (oddp x) sum x))
(sum-odd-with-loop '(1 2 3))
4
Is there a more idiomatic way to do it (that does not require cl-*
packages)?