views:

67

answers:

2

Given a function:

(defun foo (bar)
 (let ((baz bar))
    (setf baz (+ baz 1)))

I have been given to understand (perhaps incorrectly?) that baz becomes some sort of reference to bar, instead of being a true copy of bar.

What I would like to do is create a true temporary variable so that I can ensure that I can muck about with the passed in variables all I want, without having any side effects.

+3  A: 

I think I'd rather say "baz becomes a reference to the same thing that bar is a reference to". But you're right that let does not do any copying.

If you want to make a copy of bar, you certainly can, though how you do that depends on what bar is: a list, a vector, etc.

For the curious, Kent Pitman wrote a great article on the subject of "Why is there no generic COPY function?".

Ken
Ooogh. The ghost of copy constructors past rises.
Paul Nathan
+1  A: 

Typically, you can muck about with several references to a single "thing" without any issues, as long as you do not use any mutating functions (slot accessors, descructive list operations, that sort of thing).

In the case you've copied, you're using numbers and those are "always" safe (if you do arithmetic ona new copy, a new copy will be generated).

Unfortunately, there is no generic "Make a copy" function, partly because it's not obvious what "make a copy" means in all cases and partly because it's not necessarily trivial to copy circular data structures (something a generic copy function would have to be able to do).

Vatine