Squalety
Squalety

Reputation: 21

LISP Sum of list items

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?

Upvotes: 2

Views: 919

Answers (2)

Gwang-Jin Kim
Gwang-Jin Kim

Reputation: 9865

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.

Upvotes: 2

Michael Cornelius
Michael Cornelius

Reputation: 1564

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?)

Upvotes: 0

Related Questions