How to sum a list of numbers in Emacs Lisp?

天涯浪子 提交于 2019-12-31 08:45:13

问题


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?


回答1:


(apply '+ '(1 2 3))



回答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



回答3:


Linearly recursive function (sum L)

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

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



回答4:


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"



回答5:


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.




回答6:


car -> take first element of list

cdr -> take all elements of the list except first element

(defun sumup (x) (if (equal x nil) 0 (+(car x) (sumup (cdr x)))))

(sumup '(5 7 8 10))

30




回答7:


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




回答8:


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



来源:https://stackoverflow.com/questions/590579/how-to-sum-a-list-of-numbers-in-emacs-lisp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!