Clojure 不理解匿名函数的reduce
我正在读《活的Clojure》,这个Clojure 不理解匿名函数的reduce,clojure,Clojure,我正在读《活的Clojure》,这个reduce的例子让我很反感 (reduce (fn [r x] (+ r (* x x))) [1 2 3]) [1 2 3]是reduce的输入,以及匿名函数 如果向量的每个成员都被传入,那么只会填充r或x参数,其他参数从何而来 有没有办法一步一步地观察参数和输出的变化?有一种方法,但我必须承认这不是真正的描述 作为第一个参数传递的函数包含两个参数,第一个是total,第二个是current。如果仅使用两个参数调用re
reduce
的例子让我很反感
(reduce (fn [r x]
(+ r (* x x)))
[1 2 3])
[1 2 3]
是reduce
的输入,以及匿名函数
如果向量的每个成员都被传入,那么只会填充r
或x
参数,其他参数从何而来
有没有办法一步一步地观察参数和输出的变化?有一种方法,但我必须承认这不是真正的描述
作为第一个参数传递的函数包含两个参数,第一个是total,第二个是current。如果仅使用两个参数调用reduce
,则第一次迭代中的total是集合的第一项,而第一次迭代中的current是集合的第二项。如果传递三个参数,则第二个参数是初始值,在第一次迭代中作为总计传递,而集合的第一项在第一次迭代中作为当前项传递:
(reduce (fn [r x] (+ r x)) 0 [1 2 3])
将进行如下迭代:
(+ 0 1) ;; initial value and first item of the collection
(+ (+ 0 1) 2) ;; result and second item of the collection
(+ (+ (+ 0 1) 2) 3) ;; result and third item of the collection
(+ 1 2) ;; no initial value -> first and second item of the collection
(+ (+ 1 2) 3) ;; result and third item of the collection
而没有初始值
(reduce (fn [r x] (+ r x)) [1 2 3])
将进行如下迭代:
(+ 0 1) ;; initial value and first item of the collection
(+ (+ 0 1) 2) ;; result and second item of the collection
(+ (+ (+ 0 1) 2) 3) ;; result and third item of the collection
(+ 1 2) ;; no initial value -> first and second item of the collection
(+ (+ 1 2) 3) ;; result and third item of the collection
您也可以添加一个println
来查看每个迭代的输入:
(reduce
(fn [r x]
(do
(println (str "r = " r ", x = " x ", (* x x) = " (* x x) ", (+ r (* x x)) = " (+ r (* x x))))
(+ r (* x x))))
[1 2 3])
在REPL中运行它的结果是
r = 1, x = 2, (* x x) = 4, (+ r (* x x)) = 5
r = 5, x = 3, (* x x) = 9, (+ r (* x x)) = 14
14
在我看来,还有另一个答案对理解
reduce
非常有帮助: