Search code examples
lispcons

How to implement a nested list using only cons pairs?


I am making a pure Lisp interpreter, and trying to write a reader to convert lists to cons pairs.

From what I've read lists are internally cons pairs such as this:

( 1 2 3 ) = (1.(2.(3.NIL)))

but I have no clue how to implement a nested list such as the following with cons pairs

( (1 2) (3 4 ) (5 6 ) )

How is this supposed to look like unabbreviated?


Solution

  • That would be

    > '((1 . (2 . ())) . ((3 . (4 . ())) . ((5 . (6 . ())) . ())))
    '((1 2) (3 4) (5 6))
    

    or

    ? '((1 . (2 . nil)) . ((3 . (4 . nil)) . ((5 . (6 . nil)) . nil)))
    ((1 2) (3 4) (5 6))
    

    See this question for a Scheme program (which is trivial to translate to Common Lisp) that prints a list as a dotted pair.