Why does an anonymous "identity" function work in this instance:
((fn [x] x) 7) => 7
....but not a function literal?
(#(%) 7) => error
I hoping to learn something new about clojure syntax in the process of answering this question
user=> (read-string "#(%)")
(fn* [p1__3#] (p1__3#))
it expands to a function that calls the arg, rather than returning the arg... that's why the error in question sort of boils down to "7 can't be called as a function"
Thanks! Good to know about read-string for the future
(#(do %) 7) ;> 7
Just a little trick for these scenarios. The same trick is used in macros when you need to return something that "same level" as the outer context, you wrap in do.Also if you wonder why #() works this way, it's supposed to be a feature, it prevents double parentheses in many case like:
(filter #(= 1 %) ...)
Instead of:
(filter (fn [x] (= 1 x)) ...)
Where you need two set of parentheses.Same basic idea, but I tend to prefer -> to do for these cases: #(-> %).
sometimes I wonder why (defn id [x] x) isn't in core
@noisesmith Isn't that identity ?
https://clojuredocs.org/clojure.core/identity
the reason for id instead of identity is it eliminates the argument that #(do %) is terser
Do has other advantages, like: #(do (println %) %) 🤣
that's doto. anyway, I don't hate do, I just think preferring #(do %) over a well named core function is silly.
I don't know, id seems a bit of a confusing name. But I understand the feeling
Hmmm, I've used languages with id for identity.
Fair, you'd just know, but I first read it as "id" in the sense of identifier 😛
it's 'id' as in the unknowable indescribable thing that lives under the surface of ego
(german for "it")