【问题标题】:Why such implementation of partial in clojure.core为什么在 clojure.core 中这样实现部分
【发布时间】:2015-06-13 12:18:38
【问题描述】:

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

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

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

【问题讨论】:

    标签: clojure


    【解决方案1】:

    是的,这是一种性能优化。

    我不仅仅是不调用concat - 而是参数列表中的& 也需要创建一个集合。 clojure 核心库倾向于重视性能,假设语言的基本构建块将存在于每个人的性能瓶颈中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-31
      • 2016-10-01
      • 2011-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多