Closures Details

  1. Define
    a closure is a data structure storing a function together with an environment: a mapping associating each free variable of the function with the value or storage location the name was bound to at the time the closure was created.
    A closure—unlike a plain function—allows the function to access those captured variables through the closure’s reference to them, even when the function is invoked outside their scope.
    The use of closures is associated with languages where functions are first-class objects.
  1. Applications
    • Function factories, create functions with args.
    • Emulating private methods with closures
  1. Some examples in python, scheme and golang:
1
2
3
4
5
6
7
# python
def makeInc(x):
def inc(y):
# x is "closed" in the definition of inc
return y + x
return inc
1
; scheme later
1
2
3
4
5
6
7
8
9
// golang
func intSeq() func() int {
i := 0
return func() int {
i += 1
return i
}
}