减少Clojure

克里斯

有人可以解释一下下面的匿名函数如何求值吗?

(defn min-by [f coll] 
  (when (seq coll)
    (reduce (fn [min this]
        (if (> (f min) (f this)) this min))
      coll)))

(min-by :cost [{:cost 100} {:cost 36} {:cost 9}])
;=> {:cost 9}

我不明白这里的参数minthis来自何处。似乎coll可能正在隐式解构。

如何更好地了解此功能的作用?

亚瑟·乌尔费尔特

Reduce期望函数是它的第一个参数。该函数有两个参数,第一个参数是“到目前为止的结果”,第二个参数是“用于更改结果的数据”。在上面的示例中,reduce采取的功能是接收迄今为止找到的最小的事物,并将其与下一个元素进行比较。然后,它决定其中的哪一个较小,并将其保留至今。

(defn min-by [f   ;; this if a function that will be passed the smallest value 
                  ;; yet found and called again with the current value. 
                  ;; the result of these two calls will decide which is the min.
              coll] 
  (when (seq coll)
    (reduce 

      ;; first arg to reduce: a function to add something to the result

      ;; this function will be called once for each of the elements in the
      ;; collection passed as the second argument
      (fn [min     ; the result thus far 
           this]   ; the next element to include in the result

        ;; here we decide which is smaller by passing each to the function f
        ;; that was passed to min-by and compare is results for each of them.
        (if (> (f min) (f this)) this min))

      ;; second arg to reduce: the collection to work on

      ;; each element in this collection will be one of the values of
      ;; the "this" argument to the function above
      coll)))

这两个中间还有一个可选参数,用于指定结果的初始值。如果忽略此可选参数,如上例所示,则前两个参数用于在结果中生成第一个值。因此,实际上,归约函数的调用时间比输入集合中元素的数量少一倍。

user> (defn print+ [& numbers] (println "called print+") (apply + numbers))
#'builder.upload/print+
user> (reduce print+ [1 2 3])
called print+
called print+
6
user> (reduce print+ 0 [1 2 3])
called print+
called print+
called print+
6

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章