source: doc/theses/jiada_liang_MMath/user_define_enum.cfa @ efd055c

Last change on this file since efd055c was efd055c, checked in by JiadaL <j82liang@…>, 5 weeks ago

user define enum example

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