Functions That Create Functions in Clojure - Mind = Blown
20 Dec 2012
This blew my mind and kind of gave me butterflies. Is it love?
Last week I was reading a bit of Programming Clojure. I was reading a part about anonymous functions. When the third reason for anonymous functions was presented, the idea was alluring. You could create functions that create functions. It was late and I was tired and as I read the code, I did not quite grasp it. My stop came on the train and that was that.
The next morning, I opened the book again and as I read that section over, this happened...
I understood what was going on. I didn't quite have a use for it in what I was working on but I could tell that this concept was powerful. Let's take a look at the example from Programming Clojure.
1 (defn make-greeter [greeting-prefix] 2 (fn [username] (str greeting-prefix ", " username)))
Then you can do things like....
1 (def hello-greeting (make-greeter "Hello")) 2 -> #'user/hello-greeting
1 Moreover, there is no need to give each greeter a name. You can simply create a greeter and place it in the first (function) slot of a form: 2 ((make-greeter "Howdy") "pardner") 3 -> "Howdy, pardner"
Thanks Aaron and Stuart!
While working with my web server, I am running a test suite that is passing a directory when it runs. The function that I am kicking off my server with does not allow for that directory to be passed in. While talking with Doug, he had a suggestion. Use a function that will create a function. Click! I knew that technique was powerful! I am excited to be able to integrate this concept in such a relevant manner so quickly after being exposed to it. Now, I would love to stay and chat but I've got a function that births functions to write!