On page 68 from Paradigms of Artificial Intelligence Programming by Peter Norvig we have the following code:
test -> (a test)
`(this is ,test) -> (this is (a test))
`(this is ,@test) -> (this is a test)
So far so good. The splicing comma will explode the outer parentheses. However this code is not explained in the book:
`(this is . ,test) -> (this is a test)
How does it work? What is happening under the hood?
2
Answers
To understand what is going on we have to revisit how lists are implemented in common lisp. Lists are a chain of cons cells ending with
nil
value.When we insert the dot at the end of a list we are signalling the reader that our final value is not going to be
nil
but a non-empty list. As non-empty lists are just a chain of cons cells we are basically saying: "continue the chain of cons cells with the beginning of this list. (in our example this non-empty list istest
and has the value(a test)
.If our list doesn't end with
nil
, the reader will always show is this fact with a dot:From the CLHS section on [backquote][1]:
So
is equivalent to:
which is equivalent to:
So it creates a list that begins with
this is
and the tail is the contents oftest
.This parallels the syntax used to create dotted lists:
because
3
is put in theCDR
of the lastCONS
in the list, rather than puttingNIL
there as in proper lists. When you use backquote, it puts the whole list in that place, so it’s like:which is the same as