What is the Difference Between a Closure and a Function?

Is a closure just an anonymous function or does it go deeper than that?

Image for post
Image for post
The symbol for lambda often used to refer to the concept of closures.

Closures are just un-named or anonymous functions

I can easily demonstrate this is not true by creating a named closure. I will do code examples in both Python and Swift. This is the Swift version:

func makeInc(_ n: Int) -> (Int) -> Int { 
func inc(_ x: Int) -> Int {
return n + x
}
return inc
}
def make_inc(n: int):
def inc(x: int):
return n + x
return inc
$ swift
$ python
$ bpython
> let f = makeInc(10)
> f(5)
$R0: Int = 15
>>> f = make_inc(10)
>>> f(5)
15
class Incrementer { 
var n: Int

init(_ n: Int) {
self.n = n
}

func inc(_ x: Int) -> Int {
return self.n + x
}
}
class Incrementer:
def __init__(self, n: int):
self.n = n
def inc(self, x: int):
return self.n + x
> let f = Incrementer(10)
> f.inc(5)
$R0: Int = 15
>>> f = Incrementer(10)
>>> f.inc(5)
15

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

Thus here is a simple way to think of closures: Imagine a problem you solve by implementing a class that holds some state which you never need to modify. The class has only one single method. You could always replace such a solution with a closure.

Geek dad, living in Oslo, Norway with passion for UX, Julia programming, science, teaching, reading and writing.

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