Reputation: 1943
Why lists created with cons() and list() are shown differently despite the lists are equal? The first one shows items separated by dot, but second one do w/o.
> (cons 1 2)
(1 . 2)
> '(1 2)
(1 2)
I know that cons
constructs dotted pair, but in this case the lists are same but shown differently.
Upvotes: 0
Views: 126
Reputation: 259
Let me expand previous answers still further
Although we are talking about Lisp language here, I notice that a line from Page 8 and 9 of a famous Book named "The Little Schemer (4th edition)" help me understand the 2 puzzling facts altogether:
Why is (cons 1 2) does not look like '(1 2)?
Why is (cons 1 '(2)) does look like '(1 2)?
----
> (cons 1 2)
(1 . 2)
> (cons 1 '(2))
(1 2)
> '(1 2)
(1 2)
Just read the "The Laws of Cons":
The primitive
cons
takes 2 arguments.The 2nd argument to
cons
must be a list.The result is a list.
In practice: (cons A B) works for all values A and B, And
(car (cons A B)) = A
(cdr (cons A B)) = B
Upvotes: 0
Reputation: 222973
To expand on Basile's answer:
(1 2)
is a proper list of length two. That is, it contains two cons cells:
#1=(1 . #2#)
#2=(2 . ())
On the other hand,
(1 . 2)
is an improper list of length one. That is, it contains one cons cell:
#1=(1 . 2)
A non-empty proper list is a list where the last cons cell's cdr
that contains the empty list, ()
. A non-empty improper list is a list where the last cons cell's cdr
contains anything else.
Upvotes: 5
Reputation: 1
It is not the same list; a list such as
(1 2)
which is returned by your quoted (i.e. 2nd) expression is the same as the result of
(cons 1 (cons 2 ())
A proper list like above is always a single-linked list of pairs whose last pair has a nil tail.
Upvotes: 8