Fork me on GitHub
#beginners
<
2024-04-24
>
Jim Newton09:04:28

where is the summary of the #( ... % ....) syntax in the clojure documentation?

Jim Newton09:04:30

thanks, but isn't there a 2nd syntax which lets you create functions of more than one arguments?

lassemaatta09:04:31

there's also a short mention on the reader page, https://clojure.org/reference/reader#_dispatch

Jim Newton09:04:26

equivalent of Scala (_ + _ + _)

lassemaatta09:04:29

you can use %1, %2 etc. and also %&

Jim Newton09:04:45

exactly, where is the discussion of that?

lassemaatta09:04:09

check the "Anonymous function arguments" link above, it includes a description of those

1
Jim Newton09:04:10

thanks, I'd clicked the first link but not the second. didn't realize it was two links.

lassemaatta09:04:49

but also keep in mind that I feel that a lot of people do not like reading code with %1, %2, etc. and strongly prefer the more explicit (fn [arg-1 arg-2 .. form when a simple #( ... % .. ) is not enough

💯 1
Jim Newton09:04:35

Yes, I almost never use %1 %2 etc. However, I'm planning on using a lot of code from Clojure for the Brave and True for my upcoming course. And the author of that book loves the syntax. So I better explain it to my students

Jim Newton09:04:26

can someone explain the reasoning for this caveat?

daveliepmann09:04:50

That's how the expansion works. Handling it differently would introduce complexity/special-casing without much benefit, seems to me.

Akiz11:04:34

In addition, be cautious of unnecessary application of partial, as it’s easy to fall into the trap of using it excessively (map (partial vector) [1 2 3 4]) might looks sexier than (map #(vector %) [1 2 3 4])

Noah Bogart12:04:08

as i understand it, the reasoning is in two steps: fn has an implicit do context which allows for multiple expressions to be written. it doesn't look strange or require additional syntax in part because the surrounding function call is (fn ...). comparatively, the anonymous function syntax doesn't have a surrounding function call to create a do context, so the parentheses must act as a single expression. if you want the do context, write it yourself.

yuhan15:04:49

One additional pitfall I see is people naturally trying to fit the syntax into a threading macro, and being confused by the resulting error messages

(-> [3 1 4 1 5 9 2 6 5 3 5]
    frequencies
    (get 5)
    #(* % %))
Of course what's happening is a 'dumb' syntactic expansion into the nonsensical form:
(fn (get 5 (frequencies ...)) [%] (* % %))