Path: utzoo!utgpu!water!watmath!clyde!ima!think!barmar
From: barmar@think.COM (Barry Margolin)
Newsgroups: comp.lang.lisp
Subject: Re: nested function definitions
Message-ID: <22394@think.UUCP>
Date: 21 Jun 88 20:28:00 GMT
References: <5862@spool.cs.wisc.edu>
Sender: usenet@think.UUCP
Reply-To: barmar@kulla.think.com.UUCP (Barry Margolin)
Organization: Thinking Machines Corporation, Cambridge, MA
Lines: 36

In article <5862@spool.cs.wisc.edu> engber@speedy.cs.wisc.edu (Mike Engber) writes:
>What does nesting function definition do in Common Lisp? For example:
>
>(defun cube (x)
> (defun square (x)
>  (* x x))
> (* x (square x)))

Sandra gave an answer about the above definition, and described a
proposal that is currently being considered by the standardization
committee.  The above example, however, doesn't show off the more
interesting aspects of the proposed extension to the language, because
it shadows parameter variables, so no variables get closed over.
Consider instead:

(defun weirdo (x)
  (defun weirdo-internal (y)
    (+ x y))
  (weirdo-internal (sqrt x)))

What does (weirdo 4) do?  It actually has what I think of as a
first-order behavior and a second-order behavior.  The first-order
behavior is that it returns 6 (it computes (+ 4 (sqrt 4))).  However,
as Sandra pointed out, it also sets the global function binding of the
WEIRDO-INTERNAL symbol; this is the second-order behavior.  If you
were to then do (weirdo-internal 10), the returned value would be 14,
because WEIRDO-INTERNAL's function binding is a closure over the value
of X as of the last time WEIRDO was called.  If you then do (weirdo
9), it will return 12, and the next (weirdo-internal 10) will return
19.

Barry Margolin
Thinking Machines Corp.

barmar@think.com
{uunet,harvard}!think!barmar