Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 36 ยท Functions and Higher-Order Functions

Defining Functions in Clojure: defn, fn and Arities

Define Clojure functions with defn and fn, add docstrings and preconditions, use multiple arities, default arguments, variadic parameters with &, the #() shorthand, closures and recursion.

Functions are the main building block of Clojure programs. They are ordinary values: you can store them in vars and collections, pass them as arguments and return them from other functions. This lesson covers every way to define one, from named top-level functions to one-line anonymous ones.

defn: named functions

defn takes a name, an optional docstring, a parameter vector and a body. The body can contain several expressions; the function returns the value of the last one.

CLOJURE
(defn area
  "Returns the area of a rectangle."
  [width height]
  (* width height))

(area 3 4)    ; 12
(doc area)    ; shows the docstring and arglist

There is no return keyword. Everything is an expression, so the last expression is the result. A function with no arguments uses an empty vector [].

CLOJURE
(defn greet []
  (println "hello")
  :done)         ; prints hello, returns :done

Calling a function with the wrong number of arguments throws an ArityException, so (area 3) fails immediately with a clear message.

fn: anonymous functions

fn creates a function without giving it a name. It is used wherever a short function is passed to another:

CLOJURE
(fn [x] (* x x))
((fn [x] (* x x)) 5)                 ; 25   call it right away
(map (fn [x] (* x x)) [1 2 3])       ; (1 4 9)
(def square (fn [x] (* x x)))        ; same as (defn square [x] ...)

A fn may take a name that is visible only inside itself, useful for recursion or clearer stack traces: (fn fact [n] (if (<= n 1) 1 (* n (fact (dec n))))).

The #() shorthand

For very short functions, #(...) is a reader shortcut. Inside it, % is the first argument, %2 the second and %& the rest:

CLOJURE
(map #(* % %) [1 2 3])        ; (1 4 9)
(#(+ %1 %2) 3 4)              ; 7
(filter #(> % 2) [1 2 3 4])   ; (3 4)

Do not nest #() inside another #(), and do not use it for bodies with more than a single call; use fn instead. The body of #() must be a single form, so #(do (println %) %) is needed for several steps.

JS Stand-in: named and anonymous functions

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Multiple arities

One function can have several parameter lists, each with its own body. This is the Clojure answer to default arguments and overloading:

CLOJURE
(defn greet
  ([] (greet "world"))
  ([name] (greet "Hello" name))
  ([greeting name] (str greeting ", " name "!")))

(greet)                  ; "Hello, world!"
(greet "Ada")            ; "Hello, Ada!"
(greet "Welcome" "Ada")  ; "Welcome, Ada!"

The shorter arities usually delegate to the longest one with default values filled in. The correct body is chosen by the number of arguments at call time.

Variadic functions

A & in the parameter vector collects all remaining arguments into a sequence (or nil if there are none):

CLOJURE
(defn total [& numbers]
  (reduce + 0 numbers))

(total)           ; 0
(total 1 2 3)     ; 6

(defn log [level & messages]
  (println (str "[" level "]") (apply str (interpose " " messages))))

(log "INFO" "server" "started")    ; [INFO] server started

apply is the opposite tool: it spreads a collection into the arguments of a function. (apply total [1 2 3]) is the same as (total 1 2 3).

Named options with a map

For optional named arguments, take a map as the last parameter and destructure it (see Destructuring):

CLOJURE
(defn connect [host {:keys [port timeout] :or {port 80 timeout 30}}]
  {:host host :port port :timeout timeout})

(connect "example.com" {:port 8080})
;; => {:host "example.com", :port 8080, :timeout 30}
JS Stand-in: arities and variadic arguments

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Docstrings, pre- and postconditions

A docstring goes between the name and the parameters. A map just before the body can hold :pre and :post conditions that are checked at call time:

CLOJURE
(defn percent
  "Returns part as a percentage of whole."
  [part whole]
  {:pre  [(number? part) (pos? whole)]
   :post [(<= 0 %)]}
  (* 100.0 (/ part whole)))

(percent 1 4)     ; 25.0
(percent 1 0)     ; AssertionError: Assert failed: (pos? whole)

% in a :post condition stands for the return value. Conditions are for catching programmer mistakes during development. Use ex-info and exceptions for expected failures in real input.

Functions are values

Because functions are values, you can put them in a map, return them or pass them around:

CLOJURE
(def operations {:add + :sub - :mul *})
((:mul operations) 6 7)          ; 42

(defn make-adder [n]
  (fn [x] (+ x n)))

(def add5 (make-adder 5))
(add5 10)                        ; 15

make-adder returns a closure: the inner function remembers the value of n from the place where it was created, even after make-adder has returned.

JS Stand-in: closures capture their surroundings

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Recursion

Functions can call themselves. Remember that the JVM does not optimise tail calls, so for loops with many steps use loop/recur (see Loops):

CLOJURE
(defn fib [n]
  (if (< n 2)
    n
    (+ (fib (dec n)) (fib (- n 2)))))

This version is correct but becomes very slow for large n, because it recomputes the same values again and again. A better approach uses loop with two accumulators:

CLOJURE
(defn fib [n]
  (loop [a 0N b 1N i n]
    (if (zero? i)
      a
      (recur b (+ a b) (dec i)))))

(fib 10)   ; 55N

Two other helpers for self-reference: recur inside a defn jumps back to the function's start, and (defn- helper ...) keeps a private helper function out of the public API.

Ways to write a function

defn Named, documented.
fn Anonymous and inline.
#() Shortest, one expression.
Arities and & Defaults and varargs.

Functions are values, so pass them around.

1 / 2

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does a Clojure function return when it has several expressions in its body?

    There is no return keyword. The function returns the value of its last expression.
  2. 2. What does (#(+ %1 %2) 3 4) return?

    %1 and %2 are the first and second arguments, so the result is 7.
  3. 3. How do you give a function an optional argument with a default?

    Multiple arities (or an options map with :or defaults) are the usual solution.
  4. 4. What does (apply + [1 2 3]) do?

    apply spreads the collection into the argument list, so it equals (+ 1 2 3).
  5. 5. What is a closure?

    An inner function captures the local bindings of the enclosing scope.

Summary

  • defn defines named functions with an optional docstring; fn and #() define anonymous ones.
  • Multiple arities replace default arguments; & collects extra arguments; apply spreads a collection into arguments.
  • :pre and :post map entries check conditions during development.
  • Functions are values and closures capture their creation environment.
  • Use loop/recur for deep recursion.

Next: Destructuring