reduceと一般的なfold系関数との比較 - lisp-cookbook-ja/common-lisp GitHub Wiki

早見表

reduceと Scheme(srfi/R6RS)のfold系関数との比較

;;; (fold-left op 'z '(a b c d))
(reduce op '(a b c d) :initial-value 'z)

;;; (fold-right 'z '(a b c d))
(reduce op '(a b c d) :initial-value 'z :from-end T)

;;; srfi 1: (fold op 'z '(a b c d))
(reduce (lambda (x y) (op y x)) '(a b c d) :initial-value 'z)

consと組み合せた場合

(reduce #'cons '(a b c d) :initial-value 'z)
;=>  ((((Z . A) . B) . C) . D)

(reduce #'cons '(a b c d) :initial-value 'z :from-end T)
;=>  (A B C D . Z)

(reduce (lambda (x y) (cons y x)) '(a b c d) :initial-value 'z)
;=>  (D C B A . Z)

その他の違い

reducesequence全般で利用できる

(reduce (lambda (x y) (cons y x)) "abcd" :initial-value '#\z)
;=>  (#\d #\c #\b #\a . #\z)

reducesequence を一つしか取れないが、schemeのfoldは複数取ることが可能

(fold-right cons* '() '(1 2 3 4) '(a b c d))
;=>  (1 a 2 b 3 c 4 d)