Subject: Re: quest for pass-by-reference semantics in CL
From: Erik Naggum <erik@naggum.net>
Date: Wed, 01 May 2002 21:27:31 GMT
Newsgroups: comp.lang.lisp
Message-ID: <3229277251241473@naggum.net>

* Mark Coletti <mcoletti@lychnobite.org>
| But I _want_ FROB to modify its argument; i.e., I'd like
| pass-by-reference semantics.

  You want wrong.  In Common Lisp, we return values and the caller modifies
  whatever needs to be modified.  Not all languages are variations on C++
  such that you can basically continue to work in C++.  E.g., Common Lisp
  can return multiple values and programmers use this instead of pass-by-
  reference because returning more than one value is better than passing in
  pointers to and clobbering somebody else's storage space.

  However, if you are so dead set on doing this that you cannot be turned
  away from misguded application of C++ semantics, here is one way to
  accomplish this:

(defun frob (setter)
  (funcall setter 42))

(let ((a 12))
  (print a)
  (frob (lambda (value) (setf a value)))
  (print a))

  Note how the variable to be modified is captured and that you cannot
  screw around with any pointers.

  You can make this more convenient with this macro

(defmacro setter (place)
  (let ((value (make-symbol "value")))
    `(lambda (,value)
       (setf ,place ,value))))

  This technique may be used to accomplish half the pass-by-name semantics
  from Algol, but there is no way to pass in a variable that will appear as
  just a variable without undue amounts of macrology.

  But I think you should simply learn to write Common Lisp in Common Lisp.
-- 
  In a fight against something, the fight has value, victory has none.
  In a fight for something, the fight is a loss, victory merely relief.

  70 percent of American adults do not understand the scientific process.