Clojure - Pure Functions
Pure Functions
Pure functions are functions that:
- always return the same result if given the same arguments - referential transparency
- don’t cause side effects
Pure functions are easier to reason about because they are isolated and are unable to impact other parts of the program. Basicly they are stable and problem free as arithmetic.
Referential Transparency
To achieve referential transparency pure function rely only on their own argument and immutable values to determine their return value. Here is an example of a pure function and a ‘dirty’ functions.
1(defn greet
2 [name]
3 (str "Hello, " name))
4
5(greet "Duja")
6; => "Hello, Duja"
7
8(defn maybe-greet
9 [name]
10 (if (> (rand) 0.5)
11 "Hello, " name
12 "..."))
No Side Effects
A program has to have some side effects like writing to a disk, rendering to a screen and so on. But this sade effect can be potentially harmful because you can’t always be sure how running a piece of code impacts other parts of the system. When calling a function without side effect you only need to worry about the relationship between the input and the output of the function. Functions with side effects are also harder to understand and test. Having to worry about the whole system not just the one function is certinly hard. Clojure makes the job of writing functions without side effect easy because all of its core data structures are immutable meaning they can’t be changed in place. Working with immutable structures is quite different from working with their mutable counterparts so this style of programming requires getting some used to.