What is the Difference Between a Closure and a Function?

As functional programming languages have become more popular, more people are learning concepts such as closures and higher order functions.

It is hard to grasp what this is about, as there is no particular new syntax for closures or higher order functions. It isn’t described as a keyword like class, func or var, but rather relates to how a programming allows you to use functions.

A common misunderstanding is to think:

Closures are just un-named or anonymous functions

The easiest way to show this is not the case is by simply creating a named closure.

func makeInc(_ n: Int) -> (Int) -> Int { 
func inc(_ x: Int) -> Int {
return n + x
}
return inc
}

Let us try this out by firing up the terminal. We start the Swift interpreter, which gives us a REPL environment.

$ swift

Write in the code below, and then run the makeInc function:

> let f = makeInc(10)
> f(5)
$R0: Int = 15

makeInc is what we call a higher order function. That means a function which takes functions as arguments or return functions. In this case we return a function we can use to increment a number with.

When calling f(5), you can see 10 is not passed as an argument. So somehow f has retained state from when it was created. That is the key about closures. It isn't lack of naming but their ability to retain state.

This is how functional programmers tend to deal with state. If you are used to object-oriented programming you will likely solve this problem in a different way. Let’s look at the equivalent solution, using object oriented programming.

class Incrementer { 
var n: Int
init(_ n: Int) {
self.n = n
}
func inc(_ x: Int) -> Int {
return self.n + x
}
}

Now we can create an incremented object, which keeps track of how much an argument is supposed to be incremented.

> let f = Incrementer(10)
> f.inc(5)
$R0: Int = 15

You can see the usage of an object with state achieves the same as our closure. So the fundamental thing about closures is not that they look syntactically different from functions.

Closures are also functions. But when a function captures state upon its creation, we call it a closure.

So anywhere, where you would have defined a class which can be initialized with any complexity of state, but which has only one method, you can replace that with the usage of a closure.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store