Subject: Re: Can special variables hi-jack function parameters?
From: rpw3@rpw3.org (Rob Warnock)
Date: Tue, 05 Aug 2008 23:17:44 -0500
Newsgroups: comp.lang.lisp
Message-ID: <S7adnSrZ49N1uATVnZ2dnUVZ_r3inZ2d@speakeasy.net>
Drew Crampsie  <drew.crampsie@gmail.com> wrote:
+---------------
| <webmas...@flymagnetic.com> wrote:
| > If so it seems care needs to be taken when defining parameter values
| > to make sure their names don't conflict with any special variables
| > that have been set up.
| 
| Yes.. that's why we name special variables with *earmuffs*, and why
| you should never (well, rarely) use *earmuffs* for function
| parameters!
+---------------

The one place where I have sometimes found this behavior useful
is for functions with a stream parameter, where the function would
really like for all its default output *and* the output of other
functions it calls to go to the stream parameter. One can trivially
accomplish this by using the symbol *STANDARD-OUTPUT* for the
stream's formal parameter, e.g.:

    > (defun bar ()
	(format t "Hello, world!~%"))

    BAR
    > (bar)
    Hello, world!
    NIL
    > (defun foo (*standard-output*)
	(format t "Guess where this text goes?~%")
	(bar)
	(format t "And where did BAR's text go?~%"))

    FOO
    > (with-output-to-string (s)
	(foo s))

    "Guess where this text goes?
    Hello, world!
    And where did BAR's text go?
    "
    > 

Or an even simpler approach:

    > (with-output-to-string (*standard-output*)
	(bar))

    "Hello, world!
    "
    > 

In practice, a somewhat safer style might be to use a keyword
parameter with the defaults set up so that *STANDARD-OUTPUT* is
not disturbed if the stream parameter is not provided, e.g.:

    > (defun foo (&key ((:stream *standard-output*) *standard-output*))
	(format t "Guess where this text goes?~%")
	(bar)
	(format t "And where did BAR's text go?~%"))

    FOO
    > (foo)
    Guess where this text goes?
    Hello, world!
    And where did BAR's text go?
    NIL
    > (with-output-to-string (s)
	(foo :stream s))

    "Guess where this text goes?
    Hello, world!
    And where did BAR's text go?
    "
    >


-Rob

-----
Rob Warnock			<rpw3@rpw3.org>
627 26th Avenue			<URL:http://rpw3.org/>
San Mateo, CA 94403		(650)572-2607