Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Common Lisp equivalent to C enums

Tags:

I'm trying to learn some Lisp (Common Lisp) lately, and I wonder if there is a way to give constant numbers a name just like you can do in C via enums.

I don't need the full featureset of enums. In the end I just want to have fast and readable code.

I've tried globals and little functions, but that always came with a degration in performance. Just plugging the numbers into the code was always faster.

like image 628
Nils Pipenbrinck Avatar asked Feb 23 '09 16:02

Nils Pipenbrinck


1 Answers

The normal way to do enumerations in Lisp is to use symbols. Symbols get interned (replaced with pointers to their entries in a symbol table) so they are as fast as integers and as readable as enumerated constants in other languages.

So where in C you might write:

 enum {    apple,    orange,    banana, }; 

In Lisp you can just use 'apple, 'orange and 'banana directly.

If you need an enumerated type, then you can define one with deftype:

(deftype fruit () '(member apple orange banana))

and then you can use the type fruit in declare, typep, typecase and so on, and you can write generic functions that specialize on that type.

like image 137
Gareth Rees Avatar answered Oct 03 '22 01:10

Gareth Rees