Clojure - Pure Functions Powers
Pure Functions Powers
Clojure provides functions that can derive new functions from old functions.
comp
Composing pure functions is a common task in FP so Clojure provides comp to compose any
number of functions to create a new function.
1((comp inc *) 2 3)
2; => 7
Code written with comp is more elegant because it conveys more meaning.
memoize
Memoization takes advantage of referential transparency by storing the arguments passed to a function and the return value of the function. With this subsequent calls to the function with the same arguments can return the result immediately.
1(defn timed-identity
2 [x]
3 (Thread/sleep 1000)
4 x)
5
6(timed-identity "hello")
7; => "hello" after 1 second
8
9(def memo-timed-identity (memoize timed-identity))
10(memo-timed-identity "hello")
11; => "hello" after 1 second
12
13(memo-timed-identity "hello")
14; => "hello" immediately