what is a closure?

Steve Horne sh at ttsoftware.co.uk
Fri Dec 15 10:41:05 EST 2000

```On Thu, 14 Dec 2000 18:09:54 GMT, "Fredrik Lundh" <fredrik at effbot.org>
wrote:

>In the following example, the "a=a" default argument binding
>binds add's local name "a" to the value of the "a" argument
>
>            return a + b
>
>    >>> m(20)
>    30

Are you sure that's a closure? - It looks closer to currying to me.
And the definition seemed pretty close to the definition of an object
- a collection of related data and methods.

Currying, in functional languages, is the process of specialising a
function by specifying one or more of its parameters to produce a
function with fewer parameters than the original. The notation in
Python is OK, but not very convenient...

If fn_name has two parameters, you could apply currying to derive a
single-parameter function as follows...

lambda p1 : fn_name (p1, 10)  #  only works for literals
lambda p1, p2=whatever : fn_name (p1, p2)

Because the second form is a bit wordy, sometimes it is easier to have
a currying function such as...

def curry_p2_of_2 (fn, p2) :
return lambda p1, fn=fn, p2=p2 : fn (p1, p2)

This is clearly similar to your example.

Compiler Design, by Dick Grune, Henri Bal, Ceriel Jacobs and Koen
Langendoen), and something that was presented in it was a 'closure
algorithm'. This took a collection of data and some related
expressions, and repeatedly evaluated the expressions using both
original and previously derived data until all the data it was
possible to derive was fully derived.

The thing that made it a closure algorithm seemed to be the fact that
the expressions were applied repeatedly on an accumulating set of data
until no further data could be derived - the closure being the
complete collection of data.

An example would be that given the expressions A = int + (int + int),
you could represent it as two simple expressions...

A   = int + <b>
<b> = int + int

And then, given an expression to determine result types from the
parameter types for the '+' operator, the closure algorithm would work
as follows...

Step 1 - it is not possible to determine A from A = int + <b>B, as <b>
is not yet known.

Step 2 - <b> = int + int, therefore <b> = int

Step 3 - A = int + <b>, therefore A = int + int

Step 4 - A = int + int, therefore A = int.

Step 5 - Unable to find any expressions to apply for which the inputs
are known, yet the output is unknown, so terminate.

I don't claim to be an expert on this. I would simply appreciate it if
someone could clear up my confusion!

--
Steve Horne
Home : steve at lurking.demon.co.uk
Work : sh at ttsoftware.co.uk

```