How to sum a list of numbers in Emacs Lisp?

30,145

Solution 1

(apply '+ '(1 2 3))

Solution 2

If you manipulate lists and write functional code in Emacs, install dash.el library. Then you could use its -sum function:

(-sum '(1 2 3 4 5)) ; => 15

Solution 3

Linearly recursive function (sum L)

;;
;; sum
;;
(defun sum(list)    
    (if (null list)
        0

        (+ 
            (first list) 
            (sum (rest list))
        )   
    )   
)
Share:
30,145
jfs
Author by

jfs

isidore.john.r at gmail dot com

Updated on April 03, 2020

Comments

  • jfs
    jfs about 4 years

    This works:

    (+ 1 2 3)
    6
    

    This doesn't work:

    (+ '(1 2 3))
    

    This works if 'cl-*' is loaded:

    (reduce '+ '(1 2 3))
    6
    

    If reduce were always available I could write:

    (defun sum (L)
      (reduce '+ L))
    
    (sum '(1 2 3))
    6
    

    What is the best practice for defining functions such as sum?