14

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?

Johan
  • 37,479
  • 32
  • 149
  • 237

1 Answers1

15

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.

Community
  • 1
  • 1
nha
  • 17,623
  • 13
  • 87
  • 133