On Fri, Mar 14, 2003 at 04:32:17PM -0500, John Tobey wrote:
> On Fri, Mar 14, 2003 at 03:49:21PM -0500, Dan Sugalski wrote:
> > At 10:14 AM -0500 3/14/03, Andrew Pimlott wrote:
> > >
> > >A6 says that, as in Perl 5, only anonymous subs are closures.  I've
> > >always thought of the fact that Perl 5 named subs are not closures
> > >as a bug kept for compatibility.
> > 
> > Well... there's always the issue that closures are done by 
> > instantiating the sub at runtime, while named subs are instantiated 
> > at compile time, which causes some difficulties. (As the enclosing 
> > sub's lexicals instantiate at runtime, thus giving the contained sub 
> > nothing to close over)
> > 
> > Now, if the named lexically scoped sub actually got re-instantiated 
> > every time, *that* would be different.
> 
> YES.  That's what we want.  That is how Scheme and Common Lisp work.
> That would make for cleaner code.

Well, Common Lisp and Scheme don't work quite the same.

    (define (f n)
      (define (g) n))

in Scheme creates a lexically scoped function g.  If it is called
within the body of f, it uses the current (lexical) value of n.

    (defun f (n)
      (defun g () n))

in Common Lisp greates a globally visible function g when f is run,
and re-defines it every time f is run.  So wherever you run it, you
get n from the most recent call to f.  If we have

    (defun f (n)
      (defun g () n)
      (if (> n 0)
          (f (1- n)))
      (g))

then (f 4) returns 0.

To get Scheme behaviour in Lisp, you have to use a different
function:

    (defun f (n)
      (labels ((g () n))
        (if (> n 0)
            (f (1- n)))
        (g)))

Now (f 4) return 4.

I wouldn't recommend the Lisp behavior.  I'm sure the Lisp people
would get rid of it if they didn't have bigger compatibility issues
than Perl.  :-)

Andrew
_______________________________________________
Boston-pm mailing list
[EMAIL PROTECTED]
http://mail.pm.org/mailman/listinfo/boston-pm

Reply via email to