gpt4 book ai didi

clojure - 在 Clojure 中减少

转载 作者:行者123 更新时间:2023-12-01 15:37:59 27 4
gpt4 key购买 nike

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

(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)))

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

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

关于clojure - 在 Clojure 中减少,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25026159/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com