Search code examples
lispracket

Why is a literal quoted list not the same as a list built by list constructors


(equal? '(1 2) (cons 1 2)) ; #f

Why exactly are these two not equivalent considering lists are just that — illusion built on top of cons cells.


Solution

  • (cons 1 2) does not create a proper list. It creates a cons cell with two elements, both are numbers.

    A normal list is recursively defined as:

    • the empty list
    • or a cons cell with an object as the car and a list as the cdr.

    In your call 2 is not a list, but a number. The second argument to cons must be a list to get a proper list.

    (1 2)

    • in (1 2), the car element is a number, the cdr element is (2).
    • in (2), the car element is a number, the cdr element is (), the empty list.
    • () is the empty list.

    Thus (1 2) is a list according to the definition above. (cons 1 2) creates (1 . 2), which is not a list according to the definition above, since 2 is not a list.