Function Literals

Another way that Clojure comes to your aid in creating new functions is to supply an alternate, minimalistic syntax for defining them. So for those moments when even the sleek lines of fn seem like too much syntactical overhead, you can use a function literal: just a # followed by the function body, wrapped in the usual parentheses. Here, for example, are the guts of adventure? recast as a function literal:

 #(when (= (:genre %1) :adventure) %1)

Note there are no named arguments in function literals; instead they use the very shell script-ish notation of %1 to stand for the first argument, %2 for the second argument, and so on. So if we needed a function that would double a number, we might use partial or we might do this: ...

Get Getting Clojure now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.