Skip to content

clojure.core/fn

View this page on ClojureDocs

Type: macro Added: Clojure 1.0 Examples: 5 Runnable: 3
([& sigs])

params => positional-params*, or positional-params* & rest-param positional-param => binding-form rest-param => binding-form binding-form => name, or destructuring-form

Defines a function.

See https://clojure.org/reference/special_forms#fn for more information

Examples

by zmila on
by belun on
by trimtab613 on . May have evaluation errors.
by ibercode on
by terjedahl on . May have evaluation errors.

Note by Thumbnail

The signature is wrong. It should be (quoting from clojure.org)

(fn name? [params* ] exprs*)

(fn name? ([params* ] exprs*)+)

Note by terjedahl

What is the purpose of name? ?

Note by vvvvalvalval

@terjedahl name? allows for self-recursion, as well as generating more human-friendly class names; it can also make the code clearer.

Note by battlmonstr

This leaves more questions. What is the performance cost? Why (fn name...) is repeated twice? What is a "binding-form"?

The syntax looks good compared to lambda function syntax in other programming languages.

Note by bfabry

fn also supports the prepost map, the same as defn

boot.user=> (def adder (fn [x] {:post [(pos? %)]} (inc x)))
#'boot.user/adder
boot.user=> (adder -2)

java.lang.AssertionError: Assert failed: (pos? %)

Note by jimka2001

A function can be defined taking specified keyword arguments:

(defn foo [req-1 req-2 & {:keys [key-1 key-2]}
   (list req-1 req-2 key-1 key-2))

(foo a b)
(foo a b :key-1 100)
(foo a b :key-2 200)
(foo a b :key-2 100 :key-1 200)

See also


Content from the matching ClojureDocs page, with authors credited on each contribution.