Writing Higher-Order Functions

Take a look at functions as first class citizens and write higher-order functions - functions that act on functions.

In Haskell, functions are first class citizens. They are values just like integers or strings and can be parameters and results of functions. Functions that act on other functions or return functions are called higher-order functions. They play an important role in functional programming as they allow us to compose elementary functions into more powerful functions. In the lesson on currying we briefly touched upon this topic, but now we will write our own higher-order functions.

Introduction to higher-order Functions

To start, let’s look at a simple example of a higher-order function. The function applyTwice takes a function of integers as its first argument and applies it twice to its second argument.

applyTwice :: (Int -> Int) -> Int -> Int
applyTwice f x = f (f x)

The parentheses in the type declaration are necessary here, as -> normally associates to the right. We use them to make it clear that the first argument of applyTwice is a function on integers (Int -> Int), and the second argument is an Int itself.

To try it out, let’s define a few more simple functions:

double :: Int -> Int
double x = 2 * x
next :: Int -> Int 
next x = x + 1

We can then make use of applyTwice like this:

Get hands-on with 1400+ tech skills courses.