Creating an empty list in Racket
Asked Answered
D

3

6

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?

Doeskin answered 23/12, 2010 at 18:33 Comment(0)
C
15

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)
Conquian answered 23/12, 2010 at 18:39 Comment(0)
E
7

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 '())
Eindhoven answered 23/12, 2010 at 21:59 Comment(2)
Thanks. Of course, if I'd just thought about it, that solution is obvious. Thanks again, DavidDoeskin
There's also 'null' and/or 'empty', depending on which racket language you're using.Monied
J
6

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.

Jimjams answered 14/12, 2014 at 19:56 Comment(2)
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.