我目前正在编写具有未定义数量的arities的函数,所以我在clojure.core中寻找示例等等.
这是例如comp(clojure.core)的定义
(defn comp
"Takes a set of functions and returns a fn that is the composition
of those fns. The returned fn takes a variable number of args,
applies the rightmost of fns to the args, the next
fn (right-to-left) to the result, etc."
{:added "1.0"
:static true}
([] identity)
([f] f)
([f g]
(fn
([] (f (g)))
([x] (f (g x)))
([x y] (f (g x y)))
([x y z] (f (g x y z)))
([x y z & args] (f (apply g x y z args)))))
([f g & fs]
(reduce1 comp (list* f g fs))))
Run Code Online (Sandbox Code Playgroud)
如您所见,对于arities [fg],代码详细说明了2和3个参数(xy; x,y,z)的值,即使它可以直接跳转到[x&args].
有任何表现原因吗?还是会议?我想,调用apply会影响性能,我不知道.
我们通常使用最多3D功能和2个功能组合在真实生活中,也许是因为它.
谢谢
Clojure的核心库通常以不是特别惯用的方式实现,特别是出于性能原因.如果您正在编写一个对程序中的大多数代码行都很重要的函数,那么您也可以这样做,但一般情况下这并不优雅或特别建议.