Joseph Yourine
Joseph Yourine

Reputation: 1331

Clojure : Is there any reason to detail arities in functions definition?

I'm currently writing functions with undefined number of arities and I so looked for examples in clojure.core and so on.

This is for example the definition of 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))))

As you can see, for the arities [f g], the code detail the values for 2 and 3 arguments (x y ; x, y, z) even if it could just have directly jumped to [x & args].

Is there any performance reason ? Or is it a convention ? I suppose that calling apply could impact performance, I don't know.

We generally use at most 3D functions and composition of 2 functions in real lif, maybe it's because of that.

Thanks

Upvotes: 3

Views: 96

Answers (1)

johnbakers
johnbakers

Reputation: 24750

Clojure's core library is implemented often in ways that are not particularly idiomatic, specifically for performance reasons. If you are writing a function that is going to be fundamental to most of the lines of code in your program, you could do the same, but in general this is not elegant or particularly advised.

Upvotes: 5

Related Questions