Exercise 09 Higher Order Functions - MikeyYeahYeah/clojure-koans GitHub Wiki
Exercise 09 - Higher Order Functions
A higher-order function is:
- a function that takes one or more functions as arguments OR
- a function that returns a function
Map
The map function relates a sequence to another
(map (fn [x] (* 4 x)) [1 2 3])
;;=> [4 8 12]
(map (fn [x] (* x x)) [1 2 3 4 5])
;;=> [1 4 9 16 25]
You can map a named fucntion to each item in a sequence as well
(map nil? [:a :b nil :c :d])
;;=> [false false true false false]
Filter
(filter (fn [x] false) '(:anything :goes :here))
;;=> ()
(filter (fn [x] true) '(:anything :goes :here))
;;=> (:anything :goes :here)
(filter (fn [x] (<= 30)) [10 20 30 40 50 60 70 80])
;;=> [10 20 30]
Combine Map and Filter
(map (fn [x] (* x 10)) (filter (fn [x] (<= x 3)) [1 2 3 4 5 6 7 8]))
;;=> [10 20 30]
Reduce
Basic syntax for reduce:
(reduce f val coll)f= functionval= Starting Value (Optional)coll= Collection
(reduce (fn [a b] (* a b)) [1 2 3 4])
;;=> 24
In the example above, there is no starting value for reduce. Reduce will perform the following:
| a | b | (* a b) | Result |
|---|---|---|---|
| 1 | 2 | (* 1 2) | 2 |
| 2 | 3 | (* 2 3) | 6 |
| 6 | 4 | (* 6 4) | 24 |
(reduce (fn [a b] (* a b)) 100 [1 2 3 4])
;;=> 2400
In this example, we do have a starting value of 100. Essentially, it will perform the same exact operation as above, but using 100 as a starting value.
| a | b | (* a b) | Result |
|---|---|---|---|
| 100 | 1 | (* 100 1) | 100 |
| 100 | 2 | (* 100 2) | 200 |
| 200 | 3 | (* 200 3) | 600 |
| 600 | 4 | (* 600 4) | 2400 |