【问题标题】:Clojure : Is there any reason to detail arities in functions definition?Clojure:是否有任何理由详细说明函数定义中的参数?
【发布时间】:2016-05-17 08:25:58
【问题描述】:

我目前正在编写具有未定义数量的 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))))

如您所见,对于 arities [f g],代码详细说明了 2 和 3 个参数 (x y ; x, y, z) 的值,即使它可以直接跳转到 [x & args]。

有任何性能原因吗?或者它是一个约定? 我想调用apply 会影响性能,我不知道。

我们在现实生活中一般最多使用3D函数和2个函数的组合,也许是因为这个。

谢谢

【问题讨论】:

    标签: clojure arity


    【解决方案1】:

    Clojure 的核心库通常以不是特别惯用的方式实现,特别是出于性能原因。如果您正在编写一个对程序中大多数代码行至关重要的函数,您也可以这样做,但一般而言,这并不优雅或特别不建议这样做。

    【讨论】:

    • 谢谢,我在生产函数中经常使用同样的方法
    猜你喜欢
    • 2011-07-24
    • 1970-01-01
    • 1970-01-01
    • 2011-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-30
    • 2017-06-08
    相关资源
    最近更新 更多