Learn/Clojure/6. Functions
Lesson 6 of 8
Sign in

Clojure, lesson 6

Functions

Functions are the main building block of Clojure programs. You have been calling them since the first lesson; now you'll write your own.

defn

defn defines a named function. After the name comes an optional docstring, then a vector of parameters, then the body:

There is no return keyword. A function returns the value of the last form in its body. If the body has several forms, the earlier ones only matter for their side effects, such as printing.

A function must be defined before the line that calls it, because Clojure reads the file from top to bottom.

Several arities

A function can accept different numbers of arguments, each with its own body. A common use is supplying a default value:

Anonymous functions

fn creates a function without a name. It is useful when you need a small function once, for example as an argument to another function:

The short form #(...) is even more compact: is the argument (or , when there are several):

2 exercises to try what you just read.

Exercise 1

Shipping cost

Press Ctrl Enter or Check to test your code.

Exercise 2

Letter grades

Press Ctrl Enter or Check to test your code.

%
%1
%2

Keep #() for tiny one-liners; once a function needs a name for its argument to be clear, use fn.

Functions are values

A function is a value like a number or a string. You can store it in a def, pass it to another function, or return it. map, filter and reduce, which you'll meet next lesson, all take a function as their first argument. partial fixes some arguments in advance:

Scope

Parameters and let names exist only inside the function that defines them. Two functions can both have a parameter called x without any clash. Helper values that only one function needs belong in a let inside it:

Top-level defs and defns, on the other hand, are visible to everything below them in the file.

Further reading

  • Learn Clojure: Functions
  • Special Forms: fn

A courier charges 5 for a parcel of up to 1 kg, plus 2 for every kilogram above that. Write the function shipping that takes a whole number of kilograms (at least 1) and returns the cost.

The starter reads one line of weights separated by spaces and prints the cost of each, one per line. You only need to fill in shipping.

Sample input:

Sample output:

Write a function grade that turns a score from 0 to 100 into a letter: 90 or more is A, 80 or more is B, 70 or more is C, 60 or more is D, anything lower is F.

The starter reads scores, one per line, and prints each score with its letter. Fill in grade.

Sample input:

Sample output:

(defn square
  "Returns x multiplied by itself."
  [x]
  (* x x))

(defn area [width height]
  (* width height))

(println (square 7) (area 3 4))     ; 49 12
(defn greet
  ([] (greet "friend"))
  ([name] (str "Hello, " name "!")))

(greet)          ; "Hello, friend!"
(greet "Ada")    ; "Hello, Ada!"
(map (fn [p] (* p 2)) [4 10 3])     ; (8 20 6)
(map #(* % 2) [4 10 3])             ; (8 20 6)
(filter #(> % 5) [4 10 3 8])        ; (10 8)
(def add-tax (partial + 5))
(add-tax 20)                        ; 25
(defn order-cost [items]
  (let [shipping 4
        price (* items 10)]
    (+ price shipping)))
1 3 10
5
9
23
95
72
40
95 A
72 C
40 F