Higher-Order Functions

Web Development with Clojure, Third Edition — by Dmitri Sotnikov, Scot Brown (70 / 107)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Named Functions | TOC | Closures 👉

Functions that take other functions as parameters are called higher-order functions. One example of such a function is map:

​ (map #(* % %) [1 2 3 4 5])
​ =>(​1​ 4 9 16 25)

Here we pass in two parameters to the map function. The first parameter is an anonymous function that squares its argument and the second is a collection of numbers. The map function visits each item in the collection and squares it. One advantage of using higher-order functions is that we don’t have to worry about boundary conditions, such as nil checks. The iterator function handles these for us.

Another example of a higher-order function is filter. This function goes through a collection and keeps only the items matching the condition specified.

​ (filter even? [1 2 3 4 5])
​ =>(​2​ 4)

You can, of course, chain these functions together to solve problems:

​ (filter even?
​ (map #(* 3 %) [1 2 3 4 5]))
​ =>(​6​ 12)

Here we multiply each item by 3, and then we use filter to keep only the even items from the resulting sequence.

Thanks to higher-order functions, you should practically never have to write loops or explicit recursion. When you need to iterate over a collection, use a function…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.