How to sum a list of numbers in Emacs Lisp?

前端 未结 7 2124
夕颜
夕颜 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:29

    Linearly recursive function (sum L)

    ;;
    ;; sum
    ;;
    (defun sum(list)    
        (if (null list)
            0
    
            (+ 
                (first list) 
                (sum (rest list))
            )   
        )   
    )
    
    0 讨论(0)
  • 2021-01-31 09:31

    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
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-31 09:43

    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"
    
    0 讨论(0)
  • 2021-01-31 09:43

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

    0 讨论(0)
  • 2021-01-31 09:48
    (apply '+ '(1 2 3))
    
    0 讨论(0)
提交回复
热议问题