Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why So Many Cases When Defining Comp?

Tags:

clojure

The core.clj code for Clojure itself (available at https://github.com/clojure/clojure/blob/clojure-1.7.0/src/clj/clojure/core.clj) gives the following definition for comp:

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

I'm new to Clojure and trying to understand both the technical side and idiomatic style sides of it and I'm wondering what the reason is for including so many cases when two functions are passed into comp. Why bother with the [x y] and [x y z] cases at all?

like image 496
sync Avatar asked Jan 17 '26 03:01

sync


1 Answers

As Mars said, this is done for efficiency. Dispatching directly is faster than using apply. Unrolling functions like this is quite common to speed up the performance, juxt is unrolled in a similar fashion.

like image 145
Daniel Compton Avatar answered Jan 19 '26 19:01

Daniel Compton



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!