Search code examples
syntaxlisparc-lisp

Why does `(= (car x) 'z)` work?


I was stumbling through the Arc tutorial when I got sort of confused with this:

Quoted from the Arc Tutorial:

Like Common Lisp assignment, Arc's = is not just for variables, but can reach inside structures. So you can use it to modify lists:

arc> x
(a b)
arc> (= (car x) 'z)
z
arc> x
(z b)

But lisp is executed recursively, right? It says that car returns the first value in a list. So:

arc> (car x)
a

which makes sense, but then why isn't (= (car x) 'z) equal to (= a 'z), which would result in:

arc> a
z
arc> x
(a b) ; Note how this hasn't changed

but it doesn't. Instead, it appears that (= (car x) 'z) seems to have the effects of (= x (list 'z (car (cdr x)))):

arc> (= x '(a b))
(a b)
arc> (= (car x) 'z)
z
arc> x
(z b)


...


arc> (= x '(a b))
(a b)
arc> (= x (list 'z (car (cdr x))))
(z b)
arc> x
(z b)

So why exactly does (= (car x) 'z) work that way and what is it that I'm missing here?


Note: this is my first introduction to LISP.


Solution

  • If you have the book "ANSI Common Lisp", there is such sentence in chapter 3.3 Why Lisp Has No Pointers:

    One of Secrets to understanding Lisp is to realize that variables have values in the same way that lists have elements. As conses have pointers to their elements, variables have pointers to their values.

    If x is assigned a list:

    arc> (= x '(a b))
    (a b)
    

    It formulates as such, the variable x points to a list. The 1st position of the list points to the symbol a and the 2nd points to the symbol b:

    A variable x points to a list, the 1st position points to symbol a and the 2nd position to symbol b

    When car of x is assigned with 'z in (= (car x) 'z), simply the 1st position points the new symbol z.

    enter image description here

    Finally, in the expression (= a 'z), a variable a is assigned and thus points to the symbol z

    enter image description here