Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sum a list of numbers in Emacs Lisp?

Tags:

emacs

elisp

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?

like image 450
jfs Avatar asked Feb 26 '09 13:02

jfs


2 Answers

(apply '+ '(1 2 3)) 
like image 140
kmkaplan Avatar answered Sep 27 '22 16:09

kmkaplan


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 
like image 43
Mirzhan Irkegulov Avatar answered Sep 27 '22 16:09

Mirzhan Irkegulov