Hello, I want to ask about anonymous functions. In this section of the guide https://clojure-doc.org/articles/language/core_overview/#filterv, there's this anonymous function
#(if (< (count %) 5) %)
What does this anonymous function expand to? And how does it differ from the following?
#(< (count %) 5)Hi! The first function :
#(if (< (count %) 5) %)
is basically the same as :
(fn [x]
(if (< (count x) 5)
x))
So, a function that given something countable, return the thing if the count is less than 5, or nil otherwise
The second one :
#(< (count %) 5)
is basically the same as :
(fn [x] (< (count x) 5))
which is a predicate. Returns true if the thing is countable and less than 5 or false otherwise.Both will throw an exception if what you provide is not "countable"
> What does this anonymous function expand to? you can try that at the repl like :
user=> (macroexpand-1 '#(< (count %) 5))
(fn* [p1__2#] (< (count p1__2#) 5))Thanks! I just learned that you can omit the second expression in if
Yeah, you can do that, but because it is confusing when exists and is preferred, which expands to almost that :
user=> (macroexpand-1 '(when true 5))
(if true (do 5))when also wraps the body in a do so you can have multiple statements in its body