38

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?

jfs
  • 399,953
  • 195
  • 994
  • 1,670

7 Answers7

78
(apply '+ '(1 2 3))
kmkaplan
  • 18,655
  • 4
  • 51
  • 65
3

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
Mirzhan Irkegulov
  • 17,660
  • 12
  • 105
  • 166
2

Linearly recursive function (sum L)

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

        (+ 
            (first list) 
            (sum (rest list))
        )   
    )   
)
Kristo Aun
  • 526
  • 7
  • 18
0

You can define your custom function to calculate the sum of a list passed to it.

(defun sum (lst) (format t "The sum is ~s~%" (write-to-string (apply '+ lst))) 
EVAL: (sum '(1 4 6 4))
-> The sum is "15"
Sudhanshu Mishra
  • 2,024
  • 1
  • 22
  • 40
-1

This ought to do the trick:

(defun sum-list (list)
  (if list
      (+ (car list) (sum-list (cdr list)))
    0))

[source]

Edit: Here is another good link that explains car and cdr - basically they are functions that allow you to grab the first element of a list and retrieve a new list sans the first item.

Andrew Hare
  • 344,730
  • 71
  • 640
  • 635
-2

(insert (number-to-string (apply '+ '(1 2 3))))

-2

(eval (cons '+ '(1 2 3))) -- though not as good as 'reduce'

Flexo
  • 87,323
  • 22
  • 191
  • 272
user946443
  • 63
  • 4