On 2023-01-03, Jinsong Zhao <
jsz...@yeah.net> wrote:
> Hi there,
>
> I am very confused by the following code:
>
> * (setf *l* '(1 2 3 4))
> (1 2 3 4)
> * (let ((a *l*))
> (setf (car a) '(0 1)))
> (0 1)
> * *l*
> ((0 1) 2 3 4)
>
> If I change (setf (car a) ...) to (setf a ...), *l* will not be changed.
> I don't know why the value of *l* is changed.
Lists (other than the empty list nil) are made of binary pair objects
called conses. A list value is a pointer/reference to a cons whose car
holds the first item, and whose cdr holds the rest of the list:
another cons, or perhaps nil if there are no more items.
When you bind the variable a to *l*, a points to the same cons cell as
*l*. The list object has not been duplicated, only the pointer.
To understand computer programming to the fullest extent, you have to
become very familiar with pointers, because they are everywhere. Not
only machine address pointers, but pointer-like entities: symbolic links
and hard links in file systems, WWW hyperlinks, parent pointers in git
commits, object IDs in databases, ...
A key question in computer science (and mathematics) is what makes two
things X and Y "same", and there can be more than one valid answer.
E.g. two character strings X and Y can be "same" if they have the same
characters, like "abc" and "abc". But it's possible that X and Y,
if they are the same, are actually the same object; i.e. X and Y
are just different names referring to the same entity.
Under the Law of Identity (
https://en.wikipedia.org/wiki/Law_of_identity)
a thing X should always be the same as itself. The people who designed
IEEE 754 floating-point disagreed: a NaN value is not equal to itself,
even if it's the same one (same bit pattern).
On the other hand you can have a sameness notion such that, say, "John"
and "JOHN" are considered the same. Those specific two wouldn't
be the same object, but this kind of case-insensitive sameness
is compatible with the Law of Identity; "John" is still "John".
When a variable in some programming language is copied from another, we
expect the value of the copy and original to be the same (with odd
exceptions like floating-point NaN values). That sameness could be due
to the values being in fact references to the same entity; you always
have to ask that question and suspect it, almost no matter what
language you are working in.
--
TXR Programming Language:
http://nongnu.org/txr
Cygnal: Cygwin Native Application Library:
http://kylheku.com/cygnal
Mastodon: @
Kazi...@mstdn.ca