What's the name of # and % in clojure? - clojure

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.

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.)

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

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.

"#" should be the lambda character, and % represents the first argument expected

Related

Anonymous function in Clojure

Maybe this sounds ridiculous question, but it is for me still not exactly clear the difference between where the # of a anonymous function should come. For example in this example i filter the divisors of a positive number:
(filter #(zero? (mod 6 %)) (range 1 (inc 6))) ;;=> (1 2 3 6)
but putting the # right before the (mod 6 %) will cause an error. Is there a rule where in such a context my anonymous function begins, and why should the # come before (zero? ...?
This shows how the #(...) syntax is just a shorthand for (fn [x] ...):
(defn divides-6 [arg]
(zero? (mod 6 arg)))
(println (filter divides-6 (range 1 10))) ; normal function
(println (filter (fn [x] (zero? (mod 6 x))) (range 1 10))) ; anonymous function
(println (filter #(zero? (mod 6 %)) (range 1 10))) ; shorthand version
;=> (1 2 3 6)
;=> (1 2 3 6)
;=> (1 2 3 6)
Using defn is just shorthand for (def divides-6 (fn [x] ...)) (i.e. the def and fn parts are combined into defn to save a little typing). We don't need to define a global name divides-6 if we are only going to use the function once. We can just define the function inline right where it will be used. The #(...) syntax is just a shorthand version as the example shows.
Note that the full name of the form #(...) is the "anonymous function literal". You may also see it called the "function reader macro" or just the "function macro". The syntax (fn [x] ...) is called the "function special form".
Clojure's filter function takes one or two arguments; either way, the first argument must be a function. So there's no "rule" where the anonymous function is defined, as long as ultimately, the first argument to filter is a function.
However, in this case, zero? does not return a function, so (zero? #(mod 6 %)) would cause filter to throw an error. And, in fact, (zero? #(mod 6 %) doesn't make sense, either, because zero? does not take a function as an argument.
filter takes two parameters:
a predicate (a filter, which is a function), and
a collection
So, in a simple way:
(defn my-predicate [x]
(zero? (mod 6 x)))
(def my-collection
(range 1 (inc 6)))
(filter
my-filter
my-collection)
# is a clojure macro, or something that preprocess and reorganize code for you. We can see the result of a macro with macroexpand-1 :
(macroexpand-1 '#(zero? (mod 6 %)))
; (fn* [p1__4777#] (zero? (mod 6 p1__4777#)))
or in a more readable code:
(fn* [x]
(zero?
(mod 6 x))
On a single value of a collection, say 3, we can apply the above function:
( (fn* [x]
(zero?
(mod 6 x)))
3)
; true
And then back to the # version of our code, the input parameter of a function is implicitly %, so:
(
#(zero? (mod 6 %))
3)
; true
And finally, back to your original function, you see why # needs to be the function defining the predicate for the filter function:
(filter
#(zero? (mod 6 %))
(range 1 (inc 6)))
; (1 2 3 6)

What does "%&" mean in Clojure?

I solved the 58th 4clojure problem using recursion but then I looked at another persons solution and found this:
(fn [& fs] (reduce (fn [f g] #(f (apply g %&))) fs))
Which is more elegant than my solution. But I don't understand what %& means? (I do understand what % means but not when it's combined with &). Could anyone shed some light on this?
It means the "rest arguments", as per this source.
Arguments in the body are determined by the presence of argument
literals taking the form %, %n or %&. % is a synonym for %1, %n
designates the nth arg (1-based), and %& designates a rest arg.
Note that the & syntax is reminiscent of the & more arguments in function parameters (see here), but &% works inside an anonymous function shorthand.
Some code to compare anonymous functions and their anonymous function shorthand equivalent :
;; a fixed number of arguments (three in this case)
(#(println %1 %2 %3) 1 2 3)
((fn [a b c] (println a b c)) 1 2 3)
;; the result will be :
;;=>1 2 3
;;=>nil
;; a variable number of arguments (three or more in this case) :
((fn [a b c & more] (println a b c more)) 1 2 3 4 5)
(#(println %1 %2 %3 %&) 1 2 3 4 5)
;; the result will be :
;;=>1 2 3 (4 5)
;;=>nil
Note that the & more or %& syntax gives a list of the rest of the arguments.

Using % in an anonymous function

I understand that given an anonymous function I can use the parameters like %1 %2, for example
(#(+ %1 %2 %3) 2 4 6)
But solving a problem
(true? (x :a {:a nil :b 2}))
where x could be
#(nil? (%2 % %))
or
#(not (%2 % 1))
What does the % without been followed by a number means?
This is an exercise on 4clojure
Thanks in advance
The % without any number is always equivalent to %1 (i.e. the first argument to the anonymous function).
From the docs:
% is a synonym for %1, %n designates the nth arg (1-based), and %& designates a rest arg.
I've seen mentioned (can't remember where but I agree) that it is always better to include the number in %1 when the anonymous function takes more than one argument, since it is more clear to the reader.

What does %-mark mean in Clojure?

I've tried to find the answer but it's quite difficult to search just the %-mark. So I've seen %-mark sometimes but I can't understand what is its function. It would be very nice if somebody could tell the explanation.
I'm assuming this is inside an anonymous function, like #(first %) if so it means the first parameter. If there are more that one, you can number them %1,%2 etc.
So for instance
(filter #(odd? %) [1 2 3 4 5 6]) => (1 3 5)
Note: In this example you would normally just do (filter odd? [1 2 3 4 5 6])
#(blah %) is shorthand for an argument to an anonymous function. So if you're squaring each element in a list, instead of
(map (fn [x] (* x x)) [1 2 3])
you can write
(map #(* % %) [1 2 3])
i.e. substituting #(* % %) for (fn [x] (* x x)) as the anonymous function. Each will give (1 4 9)
% is just a placeholder for arguments in the #(...) reader macro witch rewrites to a (fn* ...) call. It means the first passed argument.
You can add a number after the % to indicate index number of argument, beware first argument index is 1, so % == %1.
You shall provide as many arguments to the returned function as the highest index you use in the function definition.
#(str %4 %2)
gives
(fn* [p1__680# p2__679# p3__681# p4__678#] (str p4__678# p2__679#))
and needs 4 arguments.
Observe that %4 and %2 are managed first and in reading order and non used arguments are created after by the macro filling the gaps.

walk/postwalk usage

I am going through this article on Tree Visitors in Clojure and came across the below example:
(def data [[1 :foo] [2 [3 [4 "abc"]] 5]])
(walk/postwalk #(do (println "visiting:" %) %) data)
What is the outer form of postwalk doing? I can't understand its utility. How and why is postwalk used? Any explanations will be appreciated.
I'm not sure if you're asking what #() means or what the purpose of do(form1 form2) means, so I'll answer both.
#() is a shorthand for declaring an anonymous function. Anonymous functions are useful when you're passing some function into another function.
To illustrate, look at this in the repl
; define an anonymous function
user=> #(+ %1 %2)
#<user$eval68$fn__69 user$eval68$fn__69#9fe84e>
; is equivalent to
user => (fn [a b] (+ a b))
#<user$eval1951$fn__1952 user$eval1951$fn__1952#118bd3c>
; furthermore, you could then assign your anonymous function to a var
(def f #(+ %1 %2))
; is equivalent to
(defn f [a b] (+ a b))
user=> (#(+ %1 %2) 1 2)
3
user=> (f 1 2)
3
The %n refers to the arguments to positional arguments to a function where n means nth argument, starting at 1 As a further shorthand you can use % to refer to the first argument which works well for single arg anonymous functions. This is what you have in your example.
So you example is equivalent to
(def data [[1 :foo] [2 [3 [4 "abc"]] 5]])
(defn f [x] (do (println "visiting:" x) x))
(walk/postwalk f data)
The do here is a special form, which, from the docs:
(do exprs*)
Evaluates the expressions in order and returns the value of the last. If no expressions are supplied, returns nil.
In fact defn already has an implicit do, so my example above doesn't actually need the do...
; your example is equivalent to:
(def data [[1 :foo] [2 [3 [4 "abc"]] 5]])
(defn f [x] (println "visiting:" x) x)
(walk/postwalk f data)
I had the same question today and find this necrotopik. Maybe later is better the newer. Find this on clojure api reference:
postwalk
function
Usage: (postwalk f form)
Performs a depth-first, post-order traversal of form. Calls f on
each sub-form, uses f's return value in place of the original.
Recognizes all Clojure data structures except sorted-map-by.
Consumes seqs as with doall.
Also this example from clojuredocs makes things clearer:
(use 'clojure.walk)
(let [counter (atom -1)]
(postwalk (fn [x]
[(swap! counter inc) x])
{:a 1 :b 2}))
=> [6 {2 [[0 :a] [1 1]], 5 [[3 :b] [4 2]]}]
So, postwalk replaces every subform with result of the function. It is used for updating nested structures with new values. That is why resulting function contains x or % at the end. Adding input to result leads to even more nested stucture.
In the example above it is seen as it walks through the depths of nested map stucture. It is going first on deepest elements of the map, then go up on higher level, then lurk down to the next form, then again goes up and finishes its last move on the whole form.