Search code examples
lispcommon-lispclisp

How to create (d . nil) in lisp


I am beginner in Lisp. There is a question that I cannot solve.

Show the simplest expression that Lisp will print out when you type the following expression:

’(a b (c . e) (d . nil))

I tried (cons 'a (cons 'b (cons (cons 'c 'e) (cons (cons 'd nil)))))

However, it wouldn't create (d . nil).

So, is there any way to create such a dot pair?


Solution

  • Show the simplest expression that Lisp will print out when you type the following expression

    The question does not ask you to create a dotted pair, but how the dotted pair is printed. I suppose this question aims at showing you that lists are just dotted pairs printed in a special way.

    If you write this in a REPL:

    '(a b (c . e) (d . nil))
    

    The REPL replies:

    (A B (C . E) (D))
    

    You have the exact same output if you write:

    '(a . (b . ((c . e) . ((d . nil) . nil))))
    

    Basically, (a b) is the list made of a symbol a in front of a sublist (b), written (a . (b)). Here I am only talking about how forms are read. If you write them directly in the REPL, they will first be read, then evaluated, and in that case you will get an error. That's why in the examples are quoted: an expression being quoted is not evaluated, but returned as-is.

    If you want to write code that, when evaluated, produces the cons-cell (0 . 1), you have to write this list:

    (cons 0 1)
    

    The above is a list of three elements, which could be written equally:

    (cons . (0 . (1 . nil)))
    

    Your interpreter will read this list (a symbol, two numbers) and evaluate the resulting form. That forms produces, at runtime, the following cons cell:

    (0 . 1)