1
votes

I'm trying to understand how this function work, which is an implementation of comp (from the chapter "Functional Programming" in the book Clojure for the Brave and True):

(defn two-comp
  [f g]
  (fn [& args]
    (f (apply g args))))

The idea is that it takes two functions and apply them to args. What I don't understand is how the args reach the anonymous function, since they are not entered as arguments to two-comp? How can be two-comp used this way?

1
For g that takes just one argument, (defn two-comp [f g] (fn [x] (f (g x)))) returns a function that invokes f upon the result of invoking g upon its argument. As @mipadi explains, The two-comp in the question just modifies this so that g can have any number of arguments. - Thumbnail

1 Answers

4
votes

two-comp returns an anonymous function, which in turn takes args. Look at the body of two-comp:

(fn [& args]
  (f (apply g args)))

fn creates a function, and that function definition follows. The return value of fn is what is returned from two-comp.