LISP Sum of list items

Viewed 339

I wrote this macro that rewrites e.g. (sum-expr (1 2 3)) as (+ 1 2 3):

(defmacro sum-expr (expr-list)
  `(+ ,@expr-list))

=> SUM-EXPR

For example:

(sum-expr ((+ 1 3) (* 3 4) (- 8 4)))

=> 20

How can I define an equivalent function using defun?

2 Answers

As @LeonardoDagnino already mentioned it in comment:

(defun sum-expr (lst)
  (apply #'+ lst))

Would be very lispy, but implementation-dependent CALL-ARGUMENTS-LIMIT limits in some implementations the length of lst to 50 as discussed e.g. here .Therefore, the solution with reduce is cleaner.

Sounds like you need to evaluate the expressions in your list, and then reduce the resulting list by the addition function.

We can evaluate lisp expressions with eval, which we can apply to each element of the input list with mapcar.

We can then use reduce on the resulting list to find the sum.

(defun sum-expr (list)
  (reduce #'+ (mapcar #'eval list)))

This makes a lot of assumptions about the structure and type of your input, but for a simple problem with well-understood inputs, it should be fine.

(You may be interested in Why exactly is eval evil?)

Related