We are used to in object oriented programming to pass variables into parameter arguments, return values from methods.
What higher order functions allow us to do is pass in functions themselves into other functions as parameter arguments
A popular example of a higher order function is the ‘map’ function found in various languages such as Clojure and Ruby. The map function takes a collection type and a function as it’s parameter and then applies the function on each element within the collection, finally return the result as a new collection. Pretty powerful stuff.
Another example of a function within the core clojure and ruby library is the filter function, which can take a function as a predicate, then filtering out elements from collection based on the result of that function.
Higher order functions don’t stop just there, as we can return functions as an output from a function.
Returning functions from other functions can be a way to reduce duplication. Scenarios whereby you have a conditional split and the only difference is that if result “a”, call “functionA”. result “b”, call “functionb”.
An example of passing in a function.
<br />(defn double [function x] (function (function x))) (double #(+ % 3) 6) ;=> result 12
Another example showing how we concat a collection of number and return elements odd or even depending on the function that we pass through
(defn concat-some [f col col2] ((fn [x] (filter f x)) (concat col col2))) (concat-some even? [1 2 3] [4 5 6]) ; result (2 4 6) (concat-some odd? [1 2 3] [4 5 6]) ; result (1 3 5)