Reputation: 10081
What is the name of the construct in clojure that uses # at the begining of the expression a % in the middle? For example
#(fn [a b] (% b a))
I've tried searching the documentation for it but as both characters that define it aren't alphanumeric my search hasn't been too successful.
Upvotes: 2
Views: 1725
Reputation: 6956
The #() construction is shorthand for the definition of an anonymous function. The % sign is used as shorthand for the arguments it takes.
% for the first argument. %integer for multiple arguments (ie %1 %2). %& for the rest (unused) arguments wrapped in a sequence.
=> (#(println % %2 %3 %&) 1 2 3 4 5)
1 2 3 (4 5)
You can see what function it creates by doing a macroexpand on it
#((\ %1 %2) * %2))
=> (macroexpand-1 '#((\ %1 %2) * %2))
(fn* [p1__744# p2__745#] ((\space p1__744# p2__745#) * p2__745#))
in normal words the following are the same:
#((\ %1 %2) * %2))
(fn [p1 p2] ((\ p1 p2) * p2))
Be careful to note that your example creates an anonymous function with a new anonymous function inside it.
Upvotes: 2
Reputation: 46872
It appears in (at least) two places:
Under Other Useful Functions and Macros (but that doesn't mention %1 %2 etc).
In the Reader (which parses the program) - # causes dispatch to a reader macro via a table lookup (you have to look carefully, but this does describe %1 etc)
In neither case does it have a useful name (actually, "Dispatch" could be the implied name - see second link). More generally "#" is called octothorp, amongst other things (here in Chile, "gato" (cat) for some unknown reason).
(And yes, %1 %2 are the first and second parameters, etc, while %& is "rest" - you can use just % for the first - see second link).
PS As everyone else has said, it's shorthand for a function. So (fn [a b] (+ a b))
is equivalent to #(+ %1 %2)
:
Clojure> (#(println % % %2) 1 2)
1 1 2
nil
Clojure> (#(apply println %&) 1 2 3)
1 2 3
nil
Upvotes: 6
Reputation: 370
"#" should be the lambda character, and % represents the first argument expected
Upvotes: 1
Reputation: 17497
It is a reader macro for the anonymous function declaration. See http://clojure.org/reader for a comprehensive list of reader macros.
For instance, #(* 5 %)
translates to (fn [x] (* 5 x))
.
Your example translates in reading phase to (fn [op] (fn [a b] (op a b)))
(op
is my choice of placeholder there.)
Upvotes: 8