我偶然发现了partial函数的实现cojure.core.它看起来像这样:
(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)))))
Run Code Online (Sandbox Code Playgroud)
为什么它有几个奇偶校验选项,如果它可以有一个?它只是性能优化所以concat在大多数情况下不会被调用吗?
我的意思是它看起来像这样,对吧?
(defn partial
([f] f)
([f & more]
(fn [& args] (apply f (concat more args))))
)
Run Code Online (Sandbox Code Playgroud)
我还注意到其他几个函数遵循相同的模式.
是的,这是性能优化.
我不只是不打电话concat- 这是因为&在参数列表中还需要创建一个集合.假设语言的基本构建块将出现在每个人的性能瓶颈中,那么clojure核心库往往会认真对待性能.