Beginner's 'enum' question 
Author Message
 Beginner's 'enum' question

Quote:

> Hello:

> How do I implement an 'enum' (as seen in C++) in Eiffel?

> To illustrate my question, in C++, I could declare enum constants as,

>     enum COLOR {Red, Blue, Green};

> And then, I could assign Red's value to the enum type COLOR as follows:

>     COLOR = Red;

> How do I implement equivalent code in Eiffel?  From books, I read that one can
> assign unique values as follows:

>     Red, Blue, Green : INTEGER is unique

> Beyond this, I didn't understand how to declare COLOR and assign a value to
> it.

Firstly, I hope that red, blue and green are the *only* options in the
abstraction. If that list ever could be expanded, then using an
'enum-like' feature is probably not the best. Assuming it's the right
thing to do:

You declare color like any other integer variable:

        [... somewhere ]
        color: INTEGER
        ...
        color := Red
        etc.

Now, if you want to constrain color to being either red or blue or
green, you simply say that: either in a pre- or post-condition, or a
class invariant; depending on whether the variable is a feature of a
class or a local entity. If it is the feature of a class, you could
write in the invariant:

        invariant
                (color = Red) or else (color = Blue) or else (color = Green)

Loryn Jenkins



Sat, 07 Jul 2001 03:00:00 GMT  
 Beginner's 'enum' question

Quote:

>Hello:

>How do I implement an 'enum' (as seen in C++) in Eiffel?

Loryn has already mentioned the idiom for this in Eiffel.  I just
thought I'd add something that might make life easier...

class COLOURS

feature
        Red, Gree, Blue: INTEGER is unique

        valid_colour (colour: INTEGER) is
                do
                        Result := (<<Red, Green, Blue>>).has (colour);
                end
end

Now you don't have to repeat that check everywhere you need it.

--
--
Patrick Doyle                      TINCC



Mon, 09 Jul 2001 03:00:00 GMT  
 
 [ 3 post ] 

 Relevant Pages 

1. Sorry it's beginner's question..

2. TK beginners question - how to 'beep'

3. question: 'A'..'k'

4. beginner: the 'out' instruction

5. stream('file','c','seek ='x) problem

6. Wanted: Hints'n'Tips'n'Bits'n'Bobs

7. There is an 'U'|'X'|'W'|'Z'|'-' in an arithmetic operand

8. Beginner's J question #12 - locales

9. Beginner's J question

10. Beginner's J questions, vol. 3

11. Beginner's J questions, vol. 4

12. Beginner's J question

 

 
Powered by phpBB® Forum Software