fn

added
1.0

ns
clojure.core

type
macro

(fn & sigs)

params => positional-params* , or positional-params* & next-param
positional-param => binding-form
next-param => binding-form
name => symbol

Defines a function

                ;; simple anonymous function passed to (map )
user=> (map (fn [x] (* x x)) (range 1 10))
(1 4 9 16 25 36 49 64 81) 

;; anonymous function with a name.  not so anonymous now is it?
;; this is useful in stack traces
(fn add [a b] (+ a b))

;; anonymous function with two params, the second is destructured
user=> (reduce (fn [m [k v]] (assoc m v k)) {} {:b 2 :a 1 :c 3})
{2 :b, 1 :a, 3 :c} 

;; define and instantly call an anonymous function
user=> ((fn [a b c] (+ a b c)) 2 4 6)
12

;; define and instantly call an anonymous variadic function 
;; "nums" is a list here
user=> ((fn [& nums] (/ (apply + nums) (count nums))) 1 2 3 4)
5/2 

;; define and instantly call an anonymous mixed function
;; "nums" is a list, while "int" is a number
user=> ((fn [int & nums] (+ int (/ (apply + nums) (count nums)))) 10 1 2 3 4)
25/2 

;; define and instantly call an anonymous overloaded function 
;; even though it is quite pointless
user=>  ((fn ([a] (inc a)) ([a b] (+ a b))) 3)
4


            
                ;; the shortcut form for (fn ) is #( )
;; where parameters are referred by their index with the prefix %

;; the equivalent of 
user=> ((fn [a b c] (+ a b c)) 2 4 6)
12

;; is
user=> (#(+ %1 %2 %3) 2 4 6)
12

            
                ;; shortcut form #() cannot be used for maps etc.

user=> ((fn [] {:a 1}))
{:a 1}

user=> (#({:a 1}))
ArityException Wrong number of args (0) passed to: PersistentArrayMap

user=> (#([1]))
ArityException Wrong number of args (0) passed to: PersistentVector

;; explanation for the\tfirst error:
;; #(f) is a shortcut for (fn [] (f))
;; that means (#({:a 1})) is shortcut for ((fn [] ({:a 1})))
;; which leads to the error above because you cannot apply a map to an empty
;; argument list.

;; i.e. you can only use #() shortcut if the fn body is a list.
;; As ((fn [] {:a 1})) has the same result 
;; as ((fn [] (identity {:a 1}))), you can write:

user=> (#(identity {:a 1}))
{:a 1}