#() function

syntaxsince v0.0-1853 in clojureEdit

Shorthand for creating an anonymous function. Use % arg to refer to the arguments.

  • #(...) => (fn [args] (...))

Details:

Use the following to access the implicit function arguments:

  • % or %1 for first argument.
  • %2, %3 and so on for subsequent arguments
  • %& for the rest of the arguments after the highest individually referenced argument

Note that #(1) does not create a function that returns 1, for the same reason that (1) does evaluate to 1.

#() forms cannot be nested, since this would create an ambiguity between the automatically assigned % argument names.


Examples:

Quote the form to see how the reader expands it:

'#(+ %1 %2)
;;=> (fn* [p1__11# p2__12#] (+ p1__11# p2__12#))
(map #(* 2 %) [1 2 3])
;;=> (2 4 6)

(def f #(println %1 %2 %&))
(f 1 2 3 4 5)
;; prints: 1 2 (3 4 5)

See Also:


Reader code @ tools.reader:src/main/clojure/clojure/tools/reader.clj
(defn- read-fn
  [rdr _ opts pending-forms]
  (if (thread-bound? #'arg-env)
    (throw (IllegalStateException. "Nested #()s are not allowed")))
  (binding [arg-env (sorted-map)]
    (let [form (read* (doto rdr (unread \()) true nil opts pending-forms) ;; this sets bindings
          rargs (rseq arg-env)
          args (if rargs
                 (let [higharg (long (key ( first rargs)))]
                   (let [args (loop [i 1 args (transient [])]
                                (if (> i higharg)
                                  (persistent! args)
                                  (recur (inc i) (conj! args (or (get arg-env i)
                                                                 (garg i))))))
                         args (if (arg-env -1)
                                (conj args '& (arg-env -1))
                                args)]
                     args))
                 [])]
      (list 'fn* args form))))

Reader table @ tools.reader:src/main/clojure/clojure/tools/reader.clj
(defn- dispatch-macros [ch]
  (case ch
    \^ read-meta                ;deprecated
    \' (wrapping-reader 'var)
    \( read-fn
    \= read-eval
    \{ read-set
    \< (throwing-reader "Unreadable form")
    \" read-regex
    \! read-comment
    \_ read-discard
    \? read-cond
    \: read-namespaced-map
    \# read-symbolic-value
    nil))