Why such implementation of partial in clojure.core

为君一笑 提交于 2019-12-17 14:54:51

问题


I stumbled across implementation of partial function in cojure.core. It looks like this:

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

Why it has several parity options if it could have one? Is it just performance optimisation so concat doesn't get called in most cases?

I mean it could look like this otherwise, right?

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

I also noticed several other functions follow the same pattern.


回答1:


Yes, it's a performance optimization.

I'ts not just about not calling concat - it's about the fact that & in the argument list requires a collection to be created as well. The clojure core libraries tend to take performance seriously, under the assumption that the basic building blocks of the language will be present in everyone's performance bottleneck.



来源:https://stackoverflow.com/questions/30818602/why-such-implementation-of-partial-in-clojure-core

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!