skip to Main Content

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


  1. Chosen as BEST ANSWER

    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.

    (cons 1 (cons 2 (cons 3 nil))) -> (1 2 3)
    

    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 is test 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:

    (cons 1 (cons 2 3)              -> (1 2 . 3)
    

  2. From the CLHS section on [backquote][1]:

    `(x1 x2 x3 ... xn . ,form) may be interpreted to mean

        (append [ x1] [ x2] [ x3] ... [ xn] form)
    

    where the brackets indicate a transformation of an xj as described above.

    So

    `(this is . ,test)
    

    is equivalent to:

    (append '(this) '(is) test)
    

    which is equivalent to:

    (append '(this is) test)
    

    So it creates a list that begins with this is and the tail is the contents of test.

    This parallels the syntax used to create dotted lists:

    '(1 2 . 3)
    

    because 3 is put in the CDR of the last CONS in the list, rather than putting NIL there as in proper lists. When you use backquote, it puts the whole list in that place, so it’s like:

    '(this is . (a test))
    

    which is the same as

    '(this is a test)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search