Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

clojure

arity

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

like image 378
Joseph Yourine Avatar asked Dec 05 '25 13:12

Joseph Yourine


1 Answers

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.

like image 124
johnbakers Avatar answered Dec 07 '25 16:12

johnbakers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!