Using % in an anonymous function - clojure

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.

Related

How to properly bind greater and lesser values in the loop in Clojure?

I need to bind properly the greater and lesser value in the initial binding in the loop. The values are provided in ad-hoc order, so I need to distinguish them first. The loop itself is used inside an anonymous function.
So, I need to do something like:
(#(loop [divident %1 divisor %2] (some-recursion)) greater lesser)
or, this in case of swapped arguments:
(#(loop [divident %2 divisor %1] (some-recursion)) lesser greater)
If you need values to be in order from greater to lesser or lesser to greater then you could use the functions sort and sort-by. For instance:
(sort [1 7 4 6])
;;=> (1 4 6 7)
(sort-by - [1 7 4 6])
;;=> (7 6 4 1)
So for two numbers you can easily destructure the sort result:
(let [[lesser greater] (sort [7 1])]
(println lesser greater))
;;=> 1 7
Applying that to the loop:
(defn x-1 []
(#(let [[lesser greater] (sort [%1 %2])]
(loop [bigger greater
smaller lesser]
(println smaller bigger))) 7 1))
;;=> 1 7
For two numbers, the simplest approach is just to use max and min in the loop binding:
(#(loop [dividend (max %2 %1)
divisor (min %2 %1)]
(println (format "larger: %d smaller: %d" dividend divisor)))
2 1)
Not sure that this is a proper solution, but: we can do any initial binding and than do the appropriate binding switch in the first recursion loop.
Here is an example of implementation of the Euclidean algorithm as an anonymous function:
(#(loop [dd %1 dr %2]
(if (zero? (rem dd dr))
dr
(recur dr (rem dd dr))))
858 1023)
;; -> 33
(#(loop [dd %1 dr %2]
(if (zero? (rem dd dr))
dr
(recur dr (rem dd dr))))
1023 858)
;; -> 33

Which are arguments here?

I'm a really newbie at clojure.
I have this
(defn max-val [x & xs]
(reduce #(if (< %1 %2) %2 %1) (flatten (cons x xs))))
Which are the %1 and %2 arguments?
I understand that
(flatten (cons 1 2 3)
Will return a lazy-seq, making just one argument to the #() function
Let's look at the docs for reduce
(reduce f coll) (reduce f val coll)
f should be a function of 2 arguments. If val is not supplied,
returns the result of applying f to the first 2 items in coll, then
applying f to that result and the 3rd item, etc. If coll contains no
items, f must accept no arguments as well, and reduce returns the
result of calling f with no arguments. If coll has only 1 item, it
is returned and f is not called. If val is supplied, returns the
result of applying f to val and the first item in coll, then
applying f to that result and the 2nd item, etc. If coll contains no
items, returns val and f is not called.
So it applies the function to the next item in the list, as well as the result of the previous invocation (the first time using the first two items in the list).
Imagine you call your function like this:
(reduce #(if (< %1 %2) %2 %1) '(1 2 3 4))
It will first be called with 1 and 2, returning 2. Then it will be called with the result, 2, and the next item, 3, and return 3. Then it's called with the result, 3, and the next item 4, and returns 4 as the final result.
Each step uses the result of the previous invocation as the first argument for the next time.

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.

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.

What's the name of # and % in 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