Tipperary
Tipperary

Reputation: 25

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?

Upvotes: 1

Views: 460

Answers (2)

uselpa
uselpa

Reputation: 18917

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.

Upvotes: 0

Rainer Joswig
Rainer Joswig

Reputation: 139261

CL-USER 40 > (sdraw::sdraw '( (1 2) (3 4 ) (5 6 ) ))

[*|*]------------------>[*|*]------------------>[*|*]--->NIL
 |                       |                       |
 v                       v                       v
[*|*]--->[*|*]--->NIL   [*|*]--->[*|*]--->NIL   [*|*]--->[*|*]--->NIL
 |        |              |        |              |        |
 v        v              v        v              v        v
 1        2              3        4              5        6

Upvotes: 2

Related Questions