To fold a flat list in Lisp you use reduce:
* (reduce #\'+ \'(1 2 3 4 5))
15
But what if I have an arbitrarily complex tree, a
Common Lisp does not have tree versions of map or reduce.
In fact, the only tree functions I can remember off-hand are tree-equal and subst.
However, it should not be too hard to do something like:
(defun reduce-tree (function tree &key (key #'identity))
(if (atom tree)
(funcall key tree)
(funcall function
(reduce-tree function (car tree) :key key)
(reduce-tree function (cdr tree) :key key))))
try it:
> (reduce-tree #'+ '(1 . ((2 . 3) . ((4 . 5) . 6))))
==> 21
> (reduce-tree #'+ '(1 (2) (3 (4) 5)) :key (lambda (x) (or x 0)))
==> 15