Clojure: (apply fn coll) vs (apply # (apply fn% &) coll)

I am making my way through labrepl, and I saw the code that follows this template:

;; Pattern (apply #(apply f %&) coll) ;; Concrete example user=> (apply #(apply + %&) [1 2 3 4]) 10 

This is similar to this pattern:

 ;; Pattern (apply f coll) ;; Concrete example user=> (apply + [1 2 3 4]) 10 

Are these patterns equivalent? If not, what's the difference and when will you use one over the other?

I took the previous template from the step function in the labrepl laboratory:

 (defn step "Advance the automation by one step, updating all cells." [board] (doall (map (fn [window] (apply #(apply map brians-brain-rules %&) (doall (map torus-window window)))) (torus-window board)))) 

Update: I added a specific example of each template to make the question clearer.

+6
source share
2 answers

No, there is no difference. There is no reason to write a longer form; I can only assume that it was achieved by gradually changing the code, which made sense in due time.

+4
source

In fact, both forms perform the same thing and are more or less the same. Each of them provides an anonymous function.

Using #(... is a shorthand for reading Clojure for an anonymous function. This is equivalent to (fn [arg1 & args]... but you cannot insert one anonymous function #(... inside another, and the arguments are expressed as % %2... or %1 %2... , not with a vector binding (fn [arg & args] .

Both are methods for expressing anonymous functions. #(... used for simpler functions, and (fn... used for more detailed functions.

#(... tends to make things a little neat.

0
source

Source: https://habr.com/ru/post/927121/


All Articles