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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With