lexical closures and python

John Beppu beppu at binq.org
Thu Sep 6 10:55:57 CEST 2001


[  date  ] 2001/09/06 | Thursday | 02:45 AM
[ author ] Ignacio Vazquez-Abrams <ignacio at openservices.net> 

> (which, BTW, to begin to understand I had to go through LISP 101,
> Beginning LISP, LISP for Dummies, LISP for Idiots, and 
> LISP for Complete F*cking Morons... ;) )
  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
My favorite!  ;-)
 

> Other than lambdas, you can also mention the map(), reduce(), and filter()
> functions, which as I may have heard somewhere do FP-like operations.

Those functions would definitely be good to mention.

 
> Also, I gotta ask: How the hell does JavaScript support them?
                     ^^^^^^^^^^^^
hehe.

Surprisingly, it's not very contrived.  Here's a simple example
you can save as an HTML file and try out in a JavaScript-enabled
browser.

    <html>
    <head>
        <title> js closure example </title>
    </head>
    <body>
    <script>

        // this function is a closure constructor

        function sequence_iterator(n) {
            var current = a;

            return function() {         // look, ma -- no name!
                return current++;
            }
        }


        // grande and pequeno both get closures assigned to them

        var grande  = sequence_iterator(235123);
        var pequeno = sequence_iterator(1);


        // javascript closures in action

        var i;
        for (i = 0; i < 5; i++) {
            document.write(grande() + "<br>");
            document.write(pequeno() + "<br>");
        }

    </script>
    </body>
    </html>


Notice how grande and pequeno remember the value of current, but
also notice that they each remember their own current variable.
Because current is lexically bound to a new closure each time
sequence_iterator() is invoked, grande and pequeno do not
interfere with each other.

Interesting, no?






More information about the Python-list mailing list