Higher-Order Functions

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 map. The first parameter is an anonymous function that squares its argument and the second is a collection of numbers. The map function will visit each item in the collection and square 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.

 
(​

Get Web Development with Clojure now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.