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

From: Jos Koot (jos.koot at telefonica.net)
Date: Sun Aug 12 18:24:35 EDT 2007

Yes, I think you are missing something essential. But before filling the gap you 
should first have a thorough understanding of pairs, the empty list and lists 
without referring to set-car! and set-cdr!, I think. The empty list is just a 
mark and its main use is to mark the end of a proper list. You can't put 
anything into that mark. Yes, this makes it impossible to mutate an empty list 
(sorry I mean *the* empty list, for it is a unique mark) such as to convert it 
into a non empty list. This may be confusing, for it is possible with non empty 
lists. It is not very much of a problem to make a datatype like lists that 
includes pseudo empty lists (yes plural) that can be mutated such as to become 
non empty. It is even tempting to provide an example, but I wont, for it 
probably would increase your confusion. I suggest you first play with creating 
lists by means of cons only. Given the task of forming another list out of a 
given list, first think of the original list as an immutable object and create a 
new list by means of cons and using car and cdr for extraction of the elements 
of the original list. For example: How to add an element to a list (any list, 
empty or non empty)

(define (add-element element list) (cons element list))
Of course you dont need add-element, for cons already does its job.

Now how to replace the first element of a non empty list: (of course there is 
nothing to replace in an (sorry, I mean *the*) empty list)

(define (replace-first-element new-element non-empty-list)
 (cons new-element (cdr non-empty-list)))


(define a (cons 1 ()))
(define b (replace-first-element 2 a))
a --> (1) not mutated, which usualy is nice
b --> (2)

The empty list is a unique constant. You don't want to mutate this constant and 
moreover you cant, as less you can change 1 into 2. You can make 2 from 1 by 
writing (add1 1). You can add an element to a list by writing (cons e lst).

Hope this helps, Jos Koot

----- Original Message ----- 
From: "Majorinc, Kazimir" <kazimir at chem.pmf.hr>
To: "PLT Scheme Mailing List" <plt-scheme at list.cs.brown.edu>
Sent: Sunday, August 12, 2007 10:13 PM
Subject: [plt-scheme] How to insert an element in empty list?

> 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?
> Thanks,
> Kazimir Majorinc
> _________________________________________________
>  For list-related administrative tasks:
>  http://list.cs.brown.edu/mailman/listinfo/plt-scheme

Posted on the users mailing list.