How to sum a list of numbers in Emacs Lisp?

前端 未结 7 2133
夕颜
夕颜 2021-01-31 09:08

This works:

(+ 1 2 3)
6

This doesn\'t work:

(+ \'(1 2 3))

This works if \'cl-*\' is loaded:

7条回答
  •  太阳男子
    2021-01-31 09:41

    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.

提交回复
热议问题