[REBOL] Re: How can one use named constants in switch?
From: greggirwin:mindspring at: 25-Oct-2001 11:32
Hi David,
In addition to the other replies you got, and hopefully not confusing the
issue, here are a couple other ways to look at things.
First, you could set MsgType to be the literal word matching the case you
want:
case_a: 1
case_b: 2
msgType: 'case_b
switch msgType [
case_a [print "msgA" ]
case_b [print "msgB" ]
]
Now, of course, that obviates the need for defining the case words! I don't
know the best way to emulate enums, for those of us accustomed to using
them, and I don't know that we need to, but here's a slightly more intuitive
approach which puts the words in a block:
cases: [case_a case_b]
msgType: second cases
switch msgType [
case_a [print "msgA" ]
case_b [print "msgB" ]
]
Now, you have quite a bit of flexibility using this approach as well. Being
a block itself, you can access the item you want a number of different ways.
>> first cases
== case_a
>> cases/2
== case_b
>> pick cases 2
== case_b
You can also access the entire block:
>> head cases
== [case_a case_b]
>> foreach case cases [print case]
case_a
case_b
...or find out where an item falls in the enum:
>> index? find cases 'case_a
== 1
>> index? find cases 'case_b
== 2
(note that we use a literal word for each case here)
You can also protect your block with one call to protect, which is kind of
nice.
I haven't looked into building an enum object or dialect, though you could
probably make REBOL do pretty much anything you want along those lines.
Also, I'm fairly new to REBOL myself so I don't know the pros and cons of
this approach as far as efficiency, binding issues, etc. I'd love for some
experts to chime in and give their opinions.
--Gregg