Using reduce over a tree in Lisp

后端 未结 3 456
后悔当初
后悔当初 2021-01-15 18:54

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

3条回答
  •  情歌与酒
    2021-01-15 19:11

    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
    

提交回复
热议问题