Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why such implementation of partial in clojure.core

Tags:

clojure

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.

like image 607
ma2s Avatar asked Jun 13 '15 12:06

ma2s


1 Answers

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.

like image 118
noisesmith Avatar answered Nov 04 '22 00:11

noisesmith