I'm teaching myself LISP with online text of Structure and Interpretation of Computer Programs, but it differs in small details with the Racket program I'm running to learn LISP on. For example, SICP says that the terminating element of any list is 'nil', but Racket doesn't support 'nil'. How do I create an empty list in Racket so I can test my own procedures?
Creating an empty list in Racket
The empty list is denoted '()
. So you can create a list like
(cons 1 (cons 2 (cons 3 '())))
This produces the list
'(1 2 3)
Sean's answer is correct. However, if you want to be able to type nil
, then that's easy too. Just run this once at the start of your session:
(define nil '())
Thanks. Of course, if I'd just thought about it, that solution is obvious. Thanks again, David –
Doeskin
There's also 'null' and/or 'empty', depending on which racket language you're using. –
Monied
In Racket the empty list is designated as either:
'()
or as:
null
I would say that null
is probably the more idiomatic of the two, and it dovetails consistently with the predicate null?
, which tests for the empty list.
See the docs.
I vastly prefer to use
'()
over null
. Two reasons: 1. '()
is a datum literal, not an identifier like null
is. That means you know the contents of '()
, unlike null
which can be rebound: (let ((null #f)) null)
. 2. '()
works in all Scheme implementations. null
only works in implementations (like Racket) which define it. –
Eindhoven Also
(list)
is a possibility as well as '()
and null
. –
Psychodrama © 2022 - 2024 — McMap. All rights reserved.