Wednesday, March 7, 2012

An Abrupt Introduction: Closures

A closure is created by a first class function creafing and returning a function which captures the lexical bindings of the free variables in its defining environment. Once it has captured the lexical bindings the function becomes a closure because it "closes over" those variables.

Note this means closures only exist at run time.  However, it has become common to refer to the function that will become a closure as a closure.

In practical terms a closure is a function that has data attached to it.  The data retains it's state across calls.  Here is a trivial example of a closure in python:

def return_a_closure():
    total = [0]
    def adder(num=1):
        total[0] = total[0] + num
        return total[0]
    return adder

closure = return_a_closure()
closure() # returns 1
closure() # returns 2
closure() # returns 3

When creating a closure you are not limited to binding only one function or only one piece of data.  You can even share data between multiple closures.

def return_a_closure():
    total = [0]
    def adder(num=1):
        total[0] = total[0] + num
        return total[0]

    def deducter(num=1):
        total[0] = total[0] - num
        return total[0]

    return adder, deducter

add, deduct = return_a_closure()
add()    # returns 1
add()    # returns 2
deduct() # returns 1
add()    # returns 2
deduct() # returns 1

§