The shorthand syntax for an anonymous function in Clojure can be a bit confusing (at least it was for me when I first saw it!). In this post I'll go over what it is and show that it's actually not all that scary.
The Dispatch Macro
After a quick look at the docs entry for the dispatch reader macro we see that the # (hashtag / pound / number sign / whatever you want to call it) has quite a few use cases in Clojure, and one of them is for expressing anonymous functions in a more compact way. Indeed, from that link we can see that the 5th bullet point down describes our use case:
- Anonymous function literal (#())
Nice Clojure Bridge Writeup
This blog post is an excellent writing that describes Clojure's anonymous function syntax to beginners. If you are new and just trying to wrap your head around this anonymous function syntax then i would highly recommend it.
A Quick Example
I'll try to make this example very simple to try to illustrate the point that using the dispatch reader syntax is really doing the same thing as using the "fn" function with a slight difference in how you access arguments passed into the function. In particular, in the shorthand form we use % for the first argument, %n for the nth argument, and %& for "all the rest of the arguments". Here's an example of two Clojure forms that are semantically equivalent.
The posts on this site are written and maintained by Jim Lynch. About Jim...