Let: creating a temporary variable in Common Lisp
Given a function:
(defun foo (bar)开发者_StackOverflow社区
(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.
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?".
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).
精彩评论