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

From: jerzy.karczmarczuk at info.unicaen.fr (jerzy.karczmarczuk at info.unicaen.fr)
Date: Sun Aug 12 17:59:13 EDT 2007

Bill Wood writes: 

> jerzy.karczmarczuk:

>> ...But the
>> empty list is simply an irreducible constant, no way to modify it, since it
>> has no internal structure: ...

> A fairly common technique is to use a so-called "headed list",
> consisting of a list with a dummy first element.  The list is "empty"
> when the tail of the headed list is empty, you add to the front by
> inserting a fresh cons containing the new item between the head and the
> first "real" member (or nil if it is "empty"), etc.  This way you need
> not treat the empty structure as a special case so code is simplified.

This is a trick which may or may not be useful. Still, the empty structure
IS a different animal, and "simplifying" the code in such a manner -
1. Introduces an overhead.
2. May make the code less readable, more error prone... 

== 

All this, and Matthias pedagogical answer in particular, remind me times
when I used Fortran; I remember one implementation on a CDC mainframe,
where the user *could* corrupt numerical constants, for example making that
a constant 1 (stored in memory, not an assembly-level literal...) became
equal to 2. What a mess it could produce, you can hardly imagine... 

Nowadays there are languages where the indirect access to data is standard,
for example Smalltalk. It has a command   become:
(with variants, e.g.,  basicExchangeIdentityWith: ), which give the user
the power to "assign to self", an object may suddenly become something
else, and all references to it would point to its new instance. It is a
horrible weapon! 

Jerzy Karczmarczuk 




Posted on the users mailing list.