Creating functions

Creating functions in Clojure is structurally similar to other languages: we need a name, parameters and the body. Let's start with a simple example:

(fn [r]
  (* 3.14 r r))

This function calculates (crudely) the area of a circle of radius r. A similar function in modern JavaScript would look like this:

(r) => {
  return 3.14 * r * r
}

fn is a macro for creating functions. Macros are one of the most powerful features of Clojure. Think of them as meta-code, code that creates code. We will focus on macros in the end of this book, and you will learn to create your own macros which essentially means you'll be able to extend Clojure and add new features to the language.

This is a profound statement. In most languages, new features can only emerge by updating the compiler or the interpreter. In Clojure, new features can be developed by anybody, for their own small project or for others in the open source community to enjoy. Often, important official updates to Clojure came as macros and functions, not as new versions of the compiler. That is simply impossible in most other programming languages today.

The function we've created doesn't have a name — it's anonymous. Just like before, we can assign it one by binding:

(def area (fn [r]
  (* 3.14 r r)))

And now we can call it by name:

user=> (area 2)
12.56

user=> (area 290)
264074.0

Since creating functions and binding names is a common task, Clojure comes with a handy function defn which does exactly what we did, but in a more terse form:

(defn area [r]
  (* 3.14 r r))

Let's talks about the body for a bit. It contains a single expression which is a call to * (multiplication). There are no explicit returns in Clojure. Instead, the last expression in the body is evaluated and returned. If there are several expressions, only the last one is returned:

(defn area [r]
  (* 3.14 r r)
  42)

user=> area(1)
42

Exercises

Exercise 1. Create a function perc which takes two numbers x and y and returns how many percents of y does x constitute. Example calls:

user=> (perc 50 100)
50

user=> (perc 50 200)
25

user=> (perc 1 20)
5

Exercise 2. Create a function sphere-area which calculates the surface area of a sphere using formula 4pir2. The function takes only one argument: radius. (Feel free to use the rough value 3.14 for pi.)

Exercise 3. Create a new function sphere-area-inc which is a composition of two functions: inc and sphere-area. The new function should increment the incoming radius by 1 before calculating sphere surface area. Recall that comp applies the functions from right to left.

user=> (sphere-area-inc 5)
452.16

user=> (sphere-area-inc 8)
1017.36

user=> (sphere-area-inc 0)
12.56