In elisp,
(cons 1 2) `returns`
(1 . 2)
(list 1 2) `returns`
(1 2)
What is the difference between both the outputs?
In elisp,
(cons 1 2) `returns`
(1 . 2)
(list 1 2) `returns`
(1 2)
What is the difference between both the outputs?
(cons 1 2)
creates a single cons cell like this:
---------
| 1 | 2 |
---------
Lists in Lisp are a chain of cons cells. Each cell's car
is a list element, its cdr
points to the next cell in the chain; the last one's cdr
points to the special symbol nil
. So (list 1 2)
creates a chain of cons cells like this:
--------| --------|
| 1 | ----->| 2 | ----> nil
--------| --------|
It's equivalent to (cons 1 (cons 2 nil))
If you have two things, A
and B
, you have as a given that (eq (car (cons A B)) A)
and (eq (cdr (cons A B)) B)
. That is, cons
constructs a "cons cell" (a pair) with two parts, the car
part and the cdr
part.
By convention, a pair that consists of an atom and the empty list is considered to be a list. So, (cons 2 nil)
is (2)
. By that same token, (list 1 2)
returns a similar structure to (cons 1 (cons 2 nil))
(that is, (1 2)
).
the job of cons is to add the first element to the second element
so, in your first example (cons 1 2)
the 2 is an element so adding 1 to it will create a pair (1 . 2)
the second example creates a list with 1 and 2 as element of that list
if it was like (cons 1 (list 2))
now cons will find that the second parameter is a list and the result will be (1 2)
© 2022 - 2024 — McMap. All rights reserved.