What's the difference between:
(cons 'a (cons 'b 'c)) ;; (A B . C)
and
(cons 'a '(b.c)) ;; (A B.C)
I need to create the following list ((a.b).c) using cons so i'm trying to understand what that "." represents.
L.E.: I have the following (cons (cons 'a 'b) 'c)
but it produces ((A . B) . C)
and not ((A.B).C)
(Note the extra spaces)
.
between two characters is a part of a symbol.b.c
is a symbol with a name of three characters: b, ., and c.If you enter
FOO.BAR
, then Lisp will read it as one symbol.If you enter
(FOO.BAR)
then Lisp will read it as a list with one symbol as its contents.If you enter
(FOO . BAR)
then Lisp will read it as a cons cell withFOO
as the CAR andBAR
as the CDR..
is used to separate the CAR and the CDR of a cons cell:(a . b)
. Note the space around.
.(cons 'b 'c)
creates a cons cell with the symbolb
as the CAR and the symbolc
as the CDR. It is written as(b . c)
.(cons 'a '(b.c))
creates a list of two symbols,a
andb.c
. It is written as(a b.c)
.((A.B).C)
is always printed as((A.B) . C)
. It is also not a list.((a.b) . c)
is a cons cell with the list(a.b)
as the CAR and the symbolc
as the CDR.Spaces are used to separate list tokens.
A.B
is a single token.(A.B)
is a list with a single element.(A . B)
is a cons cell withA
as car andB
as cdr.A cons cell is a pair of "things" (objects). In your case, these things are symbols, and they are named
A
,B
, etc.. The printed representation of such a cell is(A . B)
, for example. This is called "dot notation". The first element is called "car", the second "cdr".The function
cons
creates such a cell.(cons 'a 'b)
thus produces the cell(A . B)
. Note that names are always upcased internally.This is most likely what your teacher wanted, so
((A . B) . C)
is the correct output, and your code the right answer. This is a cell where the car points to another cell, and the cdr containsC
. That other cell is a cell where the car containsA
and the cdrB
.By the way, a list is a linear chain of such cons cells, such that the car always holds a value and the cdr points to the rest of the list. The last cdr points nowhere (which is called NIL in Lisp). In dot notation, a list is e.g.
(A . (B . (C . NIL)))
. Since lists are important, they can be written shorter like this:(A B C)
. If the last CDR has a value instead of NIL, it is shown in dot notation, e.g.(A . (B . (C . D))))
can be written as(A B C . D)
.If this is in the course of learning lisp, the question probably did not meant an implied "no space allowed" rule, as spaces are not significant against parenthesis, and the correct answer is the one you gave.
In particular, the space after a closing parenthesis is always added, but it's for human readability purpose only. It does not make any sense to require it not to be printed.