39

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?

2
  • Please do not change the question, open a new one. Commented Feb 26, 2009 at 15:53
  • I've rollbacked the question. Commented Feb 26, 2009 at 16:16

7 Answers 7

80
(apply '+ '(1 2 3))
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I've thought that I'm missing something trivial.
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

Comments

2

Linearly recursive function (sum L)

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

        (+ 
            (first list) 
            (sum (rest list))
        )   
    )   
)

Comments

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"

Comments

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

11 Comments

Recursion is bad in Emacs Lisp.
I was trying to avoid doing exactly that.
Most of the time, you should be able to use reduce and the varieties of map operations instead of explicitly handling cars and cdrs.
Because Emacs Lisp does not do tail call optimization. What’s more your sum-list recursion is not in tail position.
Yes. But remember not to do it with Emacs Lisp, just with Lisps that give you tail call optimization.
|
-2

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

Comments

-3

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

2 Comments

There's no need for eval. Apply does the same thing.
Yes, it was just to show that it could be done in this way as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.