source: doc/theses/jiada_liang_MMath/user_define_enum.cfa @ 38f6e66

Last change on this file since 38f6e66 was ee2f11f, checked in by Peter A. Buhr <pabuhr@…>, 3 months ago

fix user_define_enum.cfa

  • Property mode set to 100644
File size: 1.2 KB
Line 
1#include <fstream.hfa>
2#include <enum.hfa>
3#include <string.hfa>
4
5forall( E, V | TypedEnum( E, V ) | { string str( V ); } ) // routine to format value}$
6string format_enum( E e ) {
7        return label( e ) + '(' + str( value( e ) ) + ')'; // "label( value )"
8}
9enum(size_t) RGB { Red = 0xFF0000, Green = 0x00FF00, Blue = 0x0000FF };
10// string library has conversion from size_t to string
11
12struct color_code { int R, G, B; };
13enum(color_code) Rainbow {
14        Red = {255, 0, 0}, Orange = {255, 127, 0}, Yellow = {255, 255, 0}, Green = {0, 255, 0}, // ...
15};
16string str( color_code cc ) with( cc ) {
17        return str( R ) + ',' + str( G ) + ',' + str( B ); // "R,G,B"
18}
19
20enum Fruit { Apple, Banana, Cherry };                                   // C enum
21const char * label( Fruit f ) {
22        static const char * labels[] = { "Apple", "Banana", "Cherry" };
23        return labels[f];
24}
25int posn( Fruit f ) { return f; }
26int value( Fruit f ) {
27        static const char values[] = { 'a', 'b', 'c' };
28        return values[f];
29}
30string str( int f ) {
31        string s = (char)f;
32        return s;
33}
34int main() {
35        sout | format_enum( RGB.Green );                                        // "Green(65280)"}$
36        sout | format_enum( Rainbow.Green );                            // "Green(0,255,0)"}$
37        sout | format_enum( Cherry );                                           // "Cherry(c)"
38}
Note: See TracBrowser for help on using the repository browser.