[plt-scheme] How to insert an element in empty list?

From: Matthias Felleisen (matthias at ccs.neu.edu)
Date: Sun Aug 12 17:35:30 EDT 2007

On Aug 12, 2007, at 4:13 PM, Majorinc, Kazimir wrote:

> If list is not empty, it is easy (although not really trivial). But  
> how to do that with empty list, both set-first! and set-rest!  
> complain they do not work with empty lists.
>
> What does it mean, once list is empty it is empty forever?
>
> Did I miss something obvious?

Yes. Let me phrase it as a question: how do you turn a 4 into 5?  
Answer: you can't. 4 is a constant, so it makes no sense to ask how  
you can turn it into a 5.

In the same spirit, NULL is a constant. You can't insert anything  
into a constant.

Let me ask a second question: what simple mathematical action can you  
perform to produce a 5 when you give it a 4? Well, there is sub1.  
(You could also define

  (define (f x)  (- (+ x 2) 1))

and use f.)

What kind of simple action can you perform to produce a non-empty  
list when given null? Here is the simplest one I can think of:

  (lambda (x) (cons x null))

;; ---

Computations in Scheme are about producing values and combining  
values through operations into other values. If you really want  
effect-ful programming, I urge you to consider using set!, which  
changes what a variable stands for, not the data structure itself.  
[*] Using this style of programming is far simpler than producing  
value-mutating styles.

Yes, set-car! and set-cdr! exist, you want to deal with them as  
little as possible and they are going to go away, mostly.

-- Matthias

This is an email with a Footnote:

* Well, it changes the closure in which it is located




Posted on the users mailing list.