gpt4 book ai didi

clojure - 为什么在 clojure.core 中这样实现部分

转载 作者:行者123 更新时间:2023-12-02 12:44:35 24 4
gpt4 key购买 nike

我偶然发现了 cojure.corepartial 函数的实现。它看起来像这样:

(defn partial
"Takes a function f and fewer than the normal arguments to f, and
returns a fn that takes a variable number of additional args. When
called, the returned function calls f with args + additional args."
{:added "1.0"
:static true}
([f] f)
([f arg1]
(fn [& args] (apply f arg1 args)))
([f arg1 arg2]
(fn [& args] (apply f arg1 arg2 args)))
([f arg1 arg2 arg3]
(fn [& args] (apply f arg1 arg2 arg3 args)))
([f arg1 arg2 arg3 & more]
(fn [& args] (apply f arg1 arg2 arg3 (concat more args)))))

如果它可以有一个奇偶校验选项,为什么它有多个奇偶校验选项?这只是性能优化,所以在大多数情况下不会调用 concat 吗?

我的意思是,否则它可能看起来像这样,对吧?

(defn partial
([f] f)
([f & more]
(fn [& args] (apply f (concat more args))))
)

我还注意到其他几个函数也遵循相同的模式。

最佳答案

是的,这是性能优化。

我不仅仅是不调用 concat - 这是因为参数列表中的 & 也需要创建一个集合。 clojure 核心库倾向于认真对待性能,假设该语言的基本构建 block 将出现在每个人的性能瓶颈中。

关于clojure - 为什么在 clojure.core 中这样实现部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30818602/

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