- From: Pascal Costanza <pc@xxxxxxxxx>
- Date: Sat, 10 Nov 2007 01:31:16 +0100
Don Geddis wrote:
So, way back when I was first learning how to program, I think I used Pascal
(UCSD's p-system, IIRC). It had this nice concept of an "enumeration".
I'm not going to remember the syntax, but it worked something like this:
enumeration Fruit: (Apple, Banana, Carrot);
array Weight [ Fruit ];
Weight[Apple] := 3;
Weight[Banana] := 5;
Weight[Carrot] := 2;
Basically, the labels in the enumeration were syntactic sugar for integers.
So the resulting code was basically the same as:
array Weight [ 3 ];
Weight := 3;
Weight := 5;
Weight := 2;
But it was easier to read in the source code, because the mapping from
integers to real-world objects was immediately documented.
Common Lisp doesn't seem to have enumerations like this built in (unless I
missed something). You guys ever program in this style? What technique do
you use to get the same effect as I recall from Pascal? I suppose that
symbol macros would work, but that seems a little like overkill (because they
aren't context-sensitive to array accesses, for example).
Niklaus Wirth dropped enumerations in Oberon, because they are not extensible: You cannot inherit an enumeration type in one part of your code and extend with new elements in a straightforward way, because you don't know whether other parts may or may not want to extend it as well. So the question is: How do you coordinate how the numbers are assigned in a distributed fashion? This will probably lead to ugly compromises.
Instead, we can simply use symbols. You can even restrict the type of a variable:
(deftype fruit () (member 'apple 'banana 'carrot))
(defvar *f* 'apple)
(declaim (fruit *f*))
For mapping elements of an enumeration to other values, you can just use association lists, property lists, hash tables, or your own dictionary data structures.
My website: http://p-cos.net
Common Lisp Document Repository: http://cdr.eurolisp.org
Closer to MOP & ContextL: http://common-lisp.net/project/closer/
- From: Don Geddis