common-lisp Functions as first class values Summing a list


Example

The reduce function can be used to sum the elements in a list.

(reduce '+ '(1 2 3 4))
;;=> 10

By default, reduce performs a left-associative reduction, meaning that the sum 10 is computed as

(+ (+ (+ 1 2) 3) 4)

The first two elements are summed first, and then that result (3) is added to the next element (3) to produce 6, which is in turn added to 4, to produce the final result.

This is safer than using apply (e.g., in (apply '+ '(1 2 3 4)) because the length of the argument list that can be passed to apply is limited (see call-arguments-limit), and reduce will work with functions that only take two arguments.

By specifying the from-end keyword argument, reduce will process the list in the other direction, which means that the sum is computed in the reverse order. That is

(reduce '+ (1 2 3 4) :from-end t)
;;=> 10

is computing

(+ 1 (+ 2 (+ 3 4)))