I’m new to clojure, and I’ve seen anonymous functions written like:
(fn [x] (* x x))
and also like:
#(* % %)
Obviously, the second is more concise. Is there any relevant difference? Can every anonymous function be represented in either style? Is one more idiomatic?
Related to this question, I was unable to determine how to convert (fn [x] [x x]) to the latter syntax. I would appreciate a pointer to documentation that clarifies this situation.
The most important differences are:
(fn ...)can be nested,#()cannot(fn [x y] ..)or similar, rather than using%,%2,%3etc.(fn ...)for recursive usage, e.g.(fn fib [n] (if (<= n 1) 1 (+ (fib (- n 1)) (fib (- n 2)))))(fn [...] ...)since#()is a reader macro rather than a regular Clojure form.#()is more concise. But if that is a major consideration, you probably have your priorities wrong 🙂Personally my advice would be:
(fn [...] ...)in most circumstances#()only for very short inline functions, e.g.(map #(+ 2 %) (range 10))(comp func1 func2)or(partial func param1 param2)etc.