2017-08-06 51 views
1

我正在阅读生活Clojure,这个例子reduce是把我扔了。不明白减少与匿名功能

(reduce (fn [r x] 
      (+ r (* x x))) 
     [1 2 3]) 

[1 2 3]是输入到reduce,与匿名函数沿。

如果向量的每个成员都被传入,那么只会填充rx参数,其他参数来自哪里?

有没有办法一步步观察参数和输出变化?

回答

3

有一个description of the first argument on ClojureDocs,但我不得不承认这不是真正的描述。

传递作为第一个参数的函数有两个参数,第一个是,第二个是当前。如果仅用两个参数调用reduce,则第一次迭代中的总计是集合的第一项,而第一次迭代中的当前是集合的第二项。如果传递三个参数,第二个是在第一次迭代通过初始值,而集合的第一个项目,作为当前在第一次迭代中传递:

(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 

而没有初始值

(reduce (fn [r x] (+ r x)) [1 2 3]) 

会重复这样的:

(+ 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 
+1

另外还有一个答案,在我看来,可能对理解'reduce'非常有帮助:https://stackoverflow.com/a/25026200/1287643 –