[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

RE: Pass by reference in LISP



>Date: 30 Jun 92 16:38:50 U
>From: "pierce" <pierce@at-mail-server.vitro.com>
>Subject: RE: Pass by reference in LISP
>To: Info-MCL@cambridge.apple.com, jbk@world.std.com
>
>You can do the same thing in LISP that you do in C or Pascal.
>
>Consider the following example:
>
>? (defun test (ls) (rplacd (last ls) (list '(add-me))) ls)
>-> TEST
>? (let (result)
>    (setf result '(nil)) (test result) (test result) (test result) result)
>-> (NIL (ADD-ME) (ADD-ME) (ADD-ME))
>
>-Jonathan

As Jonathan points out, replacd is a dangerous operation, and
in many circles is considered to be bad style, and hence only
to be used sparingly.

It's worth pointing out that although this is technically correct,
the LAST call (inside TEST) will slow you down, especially when 
lists get big, since LAST walks the whole list each time it's
called.

In general, it's better style to 
 1) Add new elements to the beginning of a list
with something like (cons 'add-me list), rather than
walking down to the end and adding stuff there.

 2) Return the value you want from your functions, instead
of using functions to perform side-effects. This way
your code will be vastly more easy to understand and debug,
since there's no "magic" happening behind your back.
You'll find it easier to stub out code cleanly and
use TRACE to follow values as they get passed around.