减少使用cl循环设施

时间:2013-06-30 18:13:17

标签: emacs elisp

CL library manual "map over sequences"说“所有这些映射操作都可以用cl-loop宏方便地表示”但我不知道如何用cl-loop表示cl-reduce

1 个答案:

答案 0 :(得分:1)

不确定它是如何“方便”表达的,但这是我的看法:

(defun loop-reduce (func sequence &rest initial-element)
  (loop with result =
        (or (car initial-element)
            (prog1 (car sequence)
              (setf sequence (cdr sequence))))
        for x in sequence do (setf result (funcall func result x))
        finally (return result)))

(loop-reduce '+ '(1 2 3 4 5))
;; 15

(loop-reduce '+ '(1 2 3 4 5) 10)
;; 25