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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With