source: doc/theses/jiada_liang_MMath/CFAenum.tex @ dd78dbc

Last change on this file since dd78dbc was 09bdf2d, checked in by JiadaL <j82liang@…>, 9 hours ago

Add CEnum.tex

  • Property mode set to 100644
File size: 24.5 KB
Line 
1\chapter{\CFA Enumeration}
2
3% \CFA supports C enumeration using the same syntax and semantics for backwards compatibility.
4% \CFA also extends C-Style enumeration by adding a number of new features that bring enumerations inline with other modern programming languages.
5% Any enumeration extensions must be intuitive to C programmers both in syntax and semantics.
6% The following sections detail all of my new contributions to enumerations in \CFA.
7\CFA extends the enumeration declaration by parameterizing with a type (like a generic type).
8
9
10\begin{cfa}[caption={CFA Enum},captionpos=b,label={l:CFAEnum}]
11$\it enum$-specifier:
12        enum @(type-specifier$\(_{opt}\)$)@ identifier$\(_{opt}\)$ { cfa-enumerator-list }
13        enum @(type-specifier$\(_{opt}\)$)@ identifier$\(_{opt}\)$ { cfa-enumerator-list , }
14        enum @(type-specifier$\(_{opt}\)$)@ identifier
15cfa-enumerator-list:
16        cfa-enumerator
17        cfa-enumerator, cfa-enumerator-list
18cfa-enumerator:
19        enumeration-constant
20        $\it inline$ identifier
21        enumeration-constant = expression
22\end{cfa}
23
24A \newterm{\CFA enumeration}, or \newterm{\CFA enum}, has an optional type declaration in the bracket next to the @enum@ keyword.
25Without optional type declarations, the syntax defines \newterm{opaque enums}.
26Otherwise, \CFA enum with type declaration are \newterm{typed enums}.
27
28\section{Opaque Enum}
29\label{s:OpaqueEnum}
30Opaque enum is a special CFA enumeration type, where the internal representation is chosen by the compiler and hidden from users.
31Compared C enum, opaque enums are more restrictive in terms of typing, and cannot be implicitly converted to integers.
32Enumerators of opaque enum cannot have initializer. Declaring initializer in the body of opaque enum results in a compile time error.
33\begin{cfa}
34enum@()@ Planets { MERCURY, VENUS, EARTH, MARS, JUPITER, SATURN, URANUS, NEPTUNE };
35
36Planet p = URANUS;
37int i = VENUS; @// Error, VENUS cannot be converted into an integral type
38\end{cfa}
39% Each opaque enum has two @attributes@: @position@ and @label@. \CFA auto-generates @attribute functions@ @posn()@ and @label()@ for every \CFA enum to returns the respective attributes.
40Opaque enumerations have two defining properties: @label@ (name) and @order@ (position), exposed to users by predefined @attribute functions@ , with the following signatures:
41\begin{cfa}
42forall( E ) {
43        unsigned posn(E e);
44        const char * s label(E e);
45};
46\end{cfa}
47With polymorphic type parameter E being substituted by enumeration types such as @Planet@.
48
49\begin{cfa}
50unsigned i = posn(VENUS); // 1
51char * s = label(MARS); // "MARS"
52\end{cfa}
53
54\subsection{Representation}
55The underlying representation of \CFA enumeration object is its order, saved as an integral type. Therefore, the size of a \CFA enumeration is consistent with C enumeration.
56Attribute function @posn@ performs type substitution on an expression from \CFA type to integral type.
57Names of enumerators are stored in a global data structure, with @label@ maps \CFA enumeration object to corresponding data.
58
59\section{Typed Enum}
60\label{s:EnumeratorTyping}
61
62\CFA extends the enumeration declaration by parameterizing with a type (like a generic type), allowing enumerators to be assigned any values from the declared type.
63Figure~\ref{f:EumeratorTyping} shows a series of examples illustrating that all \CFA types can be use with an enumeration and each type's values used to set the enumerator constants.
64Note, the synonyms @Liz@ and @Beth@ in the last declaration.
65Because enumerators are constants, the enumeration type is implicitly @const@, so all the enumerator types in Figure~\ref{f:EumeratorTyping} are logically rewritten with @const@.
66
67\begin{figure}
68\begin{cfa}
69// integral
70        enum( @char@ ) Currency { Dollar = '$\textdollar$', Cent = '$\textcent$', Yen = '$\textyen$', Pound = '$\textsterling$', Euro = 'E' };
71        enum( @signed char@ ) srgb { Red = -1, Green = 0, Blue = 1 };
72        enum( @long long int@ ) BigNum { X = 123_456_789_012_345,  Y = 345_012_789_456_123 };
73// non-integral
74        enum( @double@ ) Math { PI_2 = 1.570796, PI = 3.141597, E = 2.718282 };
75        enum( @_Complex@ ) Plane { X = 1.5+3.4i, Y = 7+3i, Z = 0+0.5i };
76// pointer
77        enum( @char *@ ) Name { Fred = "FRED", Mary = "MARY", Jane = "JANE" };
78        int i, j, k;
79        enum( @int *@ ) ptr { I = &i,  J = &j,  K = &k };
80        enum( @int &@ ) ref { I = i,   J = j,   K = k };
81// tuple
82        enum( @[int, int]@ ) { T = [ 1, 2 ] }; $\C{// new \CFA type}$
83// function
84        void f() {...}   void g() {...}
85        enum( @void (*)()@ ) funs { F = f,  G = g };
86// aggregate
87        struct Person { char * name; int age, height; };
88@***@enum( @Person@ ) friends { @Liz@ = { "ELIZABETH", 22, 170 }, @Beth@ = Liz,
89                                                                        Jon = { "JONATHAN", 35, 190 } };
90\end{cfa}
91\caption{Enumerator Typing}
92\label{f:EumeratorTyping}
93\end{figure}
94
95An advantage of the typed enumerations is eliminating the \emph{harmonizing} problem between an enumeration and companion data \see{\VRef{s:Usage}}:
96\begin{cfa}
97enum( char * ) integral_types {
98        chr = "char", schar = "signed char", uschar = "unsigned char",
99        sshort = "signed short int", ushort = "unsigned short int",
100        sint = "signed int", usint = "unsigned int",
101        ...
102};
103\end{cfa}
104Note, the enumeration type can be a structure (see @Person@ in Figure~\ref{f:EumeratorTyping}), so it is possible to have the equivalent of multiple arrays of companion data using an array of structures.
105
106While the enumeration type can be any C aggregate, the aggregate's \CFA constructors are not used to evaluate an enumerator's value.
107\CFA enumeration constants are compile-time values (static);
108calling constructors happens at runtime (dynamic).
109
110@value@ is an @attribute@ that defined for typed enum along with position and label. @values@ of a typed enum are stored in a global array of declared typed, initialized with
111value of enumerator initializers. @value()@ functions maps an enum to an elements of the array.
112
113
114\subsection{Value Conversion}
115C has an implicit type conversion from an enumerator to its base type @int@.
116Correspondingly, \CFA has an implicit conversion from a typed enumerator to its base type. The feature that allows Typed enumeration
117seemlyless used
118\begin{cfa}
119char currency = Dollar;
120void foo( char * );
121foo( Fred );
122\end{cfa}
123
124During the resolution of expression e with \CFA enumeration type, \CFA adds @value(e)@ as an additional candidate with an extra \newterm{value} cost.
125For expression @char currency = Dollar@, the is no defined conversion from Dollar (\CFA enumeration) type to basic type and the conversion cost is @infinite@,
126thus the only valid candidate is @value(Dollar)@.
127
128@Value@ is a new category in \CFA's conversion cost model. It is defined to be a more significant factor than a @unsafe@ but weight less than @poly@.
129The resultin g conversion cost is a 8-tuple:
130@@(unsafe, value, poly, safe, sign, vars, specialization, reference)@@.
131
132\begin{cfa}
133void bar(int);
134enum(int) Month !{
135        January=31, February=29, March=31, April=30, May=31, June-30,
136        July=31, August=31, September=30, October=31, November=30, December=31
137};
138
139Month a = Februrary;    // (1), with cost (0, 1, 0, 0, 0, 0, 0, 0)
140double a = 5.5;                 // (2), with cost (1, 0, 0, 0, 0, 0, 0, 0)
141
142bar(a);
143\end{cfa}
144In the previous example, candidate (1) has an value cost to parameter type int, with is lower than (2) as an unsafe conversion from double to int.
145\CFA chooses value cost over unsafe cost and therefore @a@ of @bar(a)@ is resolved as an @Month@.
146
147\begin{cfa}
148forall(T | @CfaEnum(T)@) void bar(T);
149
150bar(a);                                 // (3), with cost (0, 0, 1, 0, 0, 0, 0, 0)
151\end{cfa}
152% @Value@ is designed to be less significant than @poly@ to allow function being generic over \CFA enumeration (see ~\ref{c:trait}).
153Being generic over @CfaEnum@ traits (a pre-defined interface for \CFA enums) is a practice in \CFA to implement functions over \CFA enumerations, as will see in chapter~\ref{c:trait}.
154@Value@ is a being a more significant cost than @poly@ implies if a overloaeded function defined for @CfaEnum@ (and other generic type), \CFA always
155try to resolve it as a @CfaEnum@, rather to insert a @value@ conversion.
156
157\subsection{Explicit Conversion}
158Explicit conversion is allowed on \CFA enumeration to an integral type, in which case \CFA converts \CFA enumeration into its underlying representation,
159which is its @position@.
160
161\section{Auto Initialization}
162
163C auto-initialization works for the integral type @int@ with constant expressions.
164\begin{cfa}
165enum Alphabet ! {
166        A = 'A', B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z,
167        a = 'a', b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z
168};
169\end{cfa}
170The complexity of the constant expression depends on the level of runtime computation the compiler implements, \eg \CC \lstinline[language={[GNU]C++}]{constexpr} provides complex compile-time computation across multiple types, which blurs the compilation/runtime boundary.
171
172% The notion of auto-initialization is generalized in \CFA enumertation E with base type T in the following way:
173When an enumerator @e@ does not have a initializer, if @e@ has enumeration type @E@ with base type @T@, \CFA auto-initialize @e@ with the following scheme:
174\begin{enumerate}
175% \item Enumerator e is the first enumerator of \CFA enumeration E with base type T. If e declares no no initializer, e is auto-initialized by the $zero\_t$ constructor of T.
176\item if e is first enumerator, e is initialized with T's @zero_t@.
177\item otherwise, if d is the enumerator defined just before e, with d has has been initialized with expression @l@ (@l@ can also be an auto-generated), e is initialized with @l++@.
178% \CFA reports a compile time error if T has no $zero\_t$ constructor.
179% Enumerator e is an enumerator of base-type T enumeration E that position i, where $i \neq 0$. And d is the enumerator with position @i-1@, e is auto-initialized with
180% the result of @value(d)++@. If operator @?++@ is not defined for type T, \CFA reports a compile time error.
181
182% Unfortunately, auto-initialization is not implemented because \CFA is only a transpiler, relying on generated C code to perform the detail work.
183% C does not have the equivalent of \CC \lstinline[language={[GNU]C++}]{constexpr}, and it is currently beyond the scope of the \CFA project to implement a complex runtime interpreter in the transpiler.
184% Nevertheless, the necessary language concepts exist to support this feature.
185\end{enumerate}
186while @?++( T )@ can be explicitly overloaded or implicitly overloaded with properly defined @one_t@ and @?+?(T, T)@.
187
188Unfortunately, auto-initialization with only constant expression is not enforced because \CFA is only a transpiler, relying on generated C code to perform the detail work.
189C does not have the equivalent of \CC \lstinline[language={[GNU]C++}]{constexpr}, and it is currently beyond the scope of the \CFA project to implement a complex runtime interpreter in the transpiler.
190Nevertheless, the necessary language concepts exist to support this feature.
191
192\section{Enumeration Inheritance}
193
194\CFA Plan-9 inheritance may be used with enumerations, where Plan-9 inheritance is containment inheritance with implicit unscoping (like a nested unnamed @struct@/@union@ in C).
195
196\begin{cfa}
197enum( char * ) Names { /* as above */ };
198enum( char * ) Names2 { @inline Names@, Jack = "JACK", Jill = "JILL" };
199enum( char * ) Names3 { @inline Names2@, Sue = "SUE", Tom = "TOM" };
200\end{cfa}
201
202Enumeration @Name2@ inherits all the enumerators and their values from enumeration @Names@ by containment, and a @Names@ enumeration is a @subtype@ of enumeration @Name2@.
203Note, that enumerators must be unique in inheritance but enumerator values may be repeated.
204
205% The enumeration type for the inheriting type must be the same as the inherited type;
206% hence the enumeration type may be omitted for the inheriting enumeration and it is inferred from the inherited enumeration, as for @Name3@.
207% When inheriting from integral types, automatic numbering may be used, so the inheritance placement left to right is important.
208Specifically, the inheritance relationship for @Names@ is:
209\begin{cfa}
210Names $\(\subset\)$ Names2 $\(\subset\)$ Names3 $\C{// enum type of Names}$
211\end{cfa}
212
213Inlined from \CFA enumeration @O@, new enumeration @N@ copies all enumerators from @O@, including those @O@ obtains through inheritance. Enumerators inherited from @O@
214keeps same @label@ and @value@, but @position@ may shift to the right if other enumerators or inline enumeration declared in prior of @inline A@.
215\begin{cfa}
216enum() Phynchocephalia { Tuatara };
217enum() Squamata { Snake, Lizard };
218enum() Lepidosauromorpha { inline Phynchocephalia, inline Squamata, Kuehneosauridae };
219\end{cfa}
220Snake, for example, has the position 0 in Squamata, but 1 in Lepidosauromorpha as Tuatara inherited from Phynchocephalia is position 0 in Lepidosauromorpha.
221
222A subtype enumeration can be casted, or implicitly converted into its supertype, with a safe cost.
223\begin{cfa}
224enum Squamata squamata_lizard = Lizard;
225posn(quamata_lizard); // 1
226enum Lepidosauromorpha lepidosauromorpha_lizard = squamata_lizard;
227posn(lepidosauromorpha_lizard); // 2
228void foo( Lepidosauromorpha l );
229foo( squamata_lizard );
230posn( (Lepidosauromorpha) squamata_lizard ); // 2
231
232Lepidosauromorpha s = Snake;
233\end{cfa}
234The last expression in the preceding example is umabigious. While both @Squamata.Snake@ and @Lepidosauromorpha.Snake@ are valid candidate, @Squamata.Snake@ has
235an associated safe cost and \CFA select the zero cost candidate @Lepidosauromorpha.Snake@.
236
237As discussed in \VRef{s:OpaqueEnum}, \CFA chooses position as a representation of \CFA enum. Conversion involves both change of typing
238and possibly @position@.
239
240When converting a subtype to a supertype, the position can only be a larger value. The difference between the position in subtype and in supertype is an "offset".
241\CFA runs a the following algorithm to determine the offset for an enumerator to a super type.
242% In a summary, \CFA loops over members (include enumerators and inline enums) of the supertype.
243% If the member is the matching enumerator, the algorithm returns its position.
244% If the member is a inline enumeration, the algorithm trys to find the enumerator in the inline enumeration. If success, it returns the position of enumerator in the inline enumeration, plus
245% the position in the current enumeration. Otherwises, it increase the offset by the size of inline enumeration.
246
247\begin{cfa}
248struct Enumerator;
249struct CFAEnum {
250        vector<variant<CFAEnum, Enumerator>> members;
251};
252pair<bool, int> calculateEnumOffset( CFAEnum dst, Enumerator e ) {
253        int offset = 0;
254        for( auto v: dst.members ) {
255                if ( v.holds_alternative<Enumerator>() ) {
256                        auto m = v.get<Enumerator>();
257                        if ( m == e ) return make_pair( true, 0 );
258                        offset++;
259                } else {
260                        auto p = calculateEnumOffset( v, e );
261                        if ( p.first ) return make_pair( true, offset + p.second );
262                        offset += p.second;
263                }
264        }
265        return make_pair( false, offset );
266}
267\end{cfa}
268
269% \begin{cfa}
270% Names fred = Name.Fred;
271% (Names2) fred; (Names3) fred; (Name3) Names.Jack;  $\C{// cast to super type}$
272% Names2 fred2 = fred; Names3 fred3 = fred2; $\C{// assign to super type}$
273% \end{cfa}
274For the given function prototypes, the following calls are valid.
275\begin{cquote}
276\begin{tabular}{ll}
277\begin{cfa}
278void f( Names );
279void g( Names2 );
280void h( Names3 );
281void j( const char * );
282\end{cfa}
283&
284\begin{cfa}
285f( Fred );
286g( Fred );   g( Jill );
287h( Fred );   h( Jill );   h( Sue );
288j( Fred );    j( Jill );    j( Sue );    j( "WILL" );
289\end{cfa}
290\end{tabular}
291\end{cquote}
292Note, the validity of calls is the same for call-by-reference as for call-by-value, and @const@ restrictions are the same as for other types.
293
294\section{Enumerator Control Structures}
295
296Enumerators can be used in multiple contexts.
297In most programming languages, an enumerator is implicitly converted to its value (like a typed macro substitution).
298However, enumerator synonyms and typed enumerations make this implicit conversion to value incorrect in some contexts.
299In these contexts, a programmer's intuition assumes an implicit conversion to position.
300
301For example, an intuitive use of enumerations is with the \CFA @switch@/@choose@ statement, where @choose@ performs an implicit @break@ rather than a fall-through at the end of a @case@ clause.
302(For this discussion, ignore the fact that @case@ requires a compile-time constant.)
303\begin{cfa}[belowskip=0pt]
304enum Count { First, Second, Third, Fourth };
305Count e;
306\end{cfa}
307\begin{cquote}
308\setlength{\tabcolsep}{15pt}
309\noindent
310\begin{tabular}{@{}ll@{}}
311\begin{cfa}[aboveskip=0pt]
312
313choose( e ) {
314        case @First@: ...;
315        case @Second@: ...;
316        case @Third@: ...;
317        case @Fourth@: ...;
318}
319\end{cfa}
320&
321\begin{cfa}[aboveskip=0pt]
322// rewrite
323choose( @value@( e ) ) {
324        case @value@( First ): ...;
325        case @value@( Second ): ...;
326        case @value@( Third ): ...;
327        case @value@( Fourth ): ...;
328}
329\end{cfa}
330\end{tabular}
331\end{cquote}
332Here, the intuitive code on the left is implicitly transformed into the standard implementation on the right, using the value of the enumeration variable and enumerators.
333However, this implementation is fragile, \eg if the enumeration is changed to:
334\begin{cfa}
335enum Count { First, Second, Third @= First@, Fourth };
336\end{cfa}
337making @Third == First@ and @Fourth == Second@, causing a compilation error because of duplicate @case@ clauses.
338To better match with programmer intuition, \CFA toggles between value and position semantics depending on the language context.
339For conditional clauses and switch statements, \CFA uses the robust position implementation.
340\begin{cfa}
341if ( @posn@( e ) < posn( Third ) ) ...
342choose( @posn@( e ) ) {
343        case @posn@( First ): ...;
344        case @posn@( Second ): ...;
345        case @posn@( Third ): ...;
346        case @posn@( Fourth ): ...;
347}
348\end{cfa}
349
350\CFA provides a special form of for-control for enumerating through an enumeration, where the range is a type.
351\begin{cfa}
352for ( cx; @Count@ ) { sout | cx | nonl; } sout | nl;
353for ( cx; +~= Count ) { sout | cx | nonl; } sout | nl;
354for ( cx; -~= Count ) { sout | cx | nonl; } sout | nl;
355First Second Third Fourth
356First Second Third Fourth
357Fourth Third Second First
358\end{cfa}
359The enumeration type is syntax sugar for looping over all enumerators and assigning each enumerator to the loop index, whose type is inferred from the range type.
360The prefix @+~=@ or @-~=@ iterate forward or backwards through the inclusive enumeration range, where no prefix defaults to @+~=@.
361
362C has an idiom for @if@ and loop predicates of comparing the predicate result ``not equal to 0''.
363\begin{cfa}
364if ( x + y /* != 0 */ ) ...
365while ( p /* != 0 */ ) ...
366\end{cfa}
367This idiom extends to enumerations because there is a boolean conversion in terms of the enumeration value, if and only if such a conversion is available.
368For example, such a conversion exists for all numerical types (integral and floating-point).
369It is possible to explicitly extend this idiom to any typed enumeration by overloading the @!=@ operator.
370\begin{cfa}
371bool ?!=?( Name n, zero_t ) { return n != Fred; }
372Name n = Mary;
373if ( n ) ... // result is true
374\end{cfa}
375Specialize meanings are also possible.
376\begin{cfa}
377enum(int) ErrorCode { Normal = 0, Slow = 1, Overheat = 1000, OutOfResource = 1001 };
378bool ?!=?( ErrorCode ec, zero_t ) { return ec >= Overheat; }
379ErrorCode code = ...;
380if ( code ) { problem(); }
381\end{cfa}
382
383
384\section{Enumeration Dimension}
385
386\VRef{s:EnumeratorTyping} introduced the harmonizing problem between an enumeration and secondary information.
387When possible, using a typed enumeration for the secondary information is the best approach.
388However, there are times when combining these two types is not possible.
389For example, the secondary information might precede the enumeration and/or its type is needed directly to declare parameters of functions.
390In these cases, having secondary arrays of the enumeration size are necessary.
391
392To support some level of harmonizing in these cases, an array dimension can be defined using an enumerator type, and the enumerators used as subscripts.
393\begin{cfa}
394enum E { A, B, C, N }; // possibly predefined
395float H1[N] = { [A] : 3.4, [B] : 7.1, [C] : 0.01 }; // C
396float H2[@E@] = { [A] : 3.4, [B] : 7.1, [C] : 0.01 }; // CFA
397\end{cfa}
398(Note, C uses the symbol, @'='@ for designator initialization, but \CFA had to change to @':'@ because of problems with tuple syntax.)
399This approach is also necessary for a predefined typed enumeration (unchangeable), when additional secondary-information need to be added.
400
401
402\section{Enumeration I/O}
403
404As seen in multiple examples, enumerations can be printed and the default property printed is the enumerator's label, which is similar in other programming languages.
405However, very few programming languages provide a mechanism to read in enumerator values.
406Even the @boolean@ type in many languages does not have a mechanism for input using the enumerators @true@ or @false@.
407\VRef[Figure]{f:EnumerationI/O} show \CFA enumeration input based on the enumerator labels.
408When the enumerator labels are packed together in the input stream, the input algorithm scans for the longest matching string.
409For basic types in \CFA, the constants use to initialize a variable in a program are available to initialize a variable using input, where strings constants can be quoted or unquoted.
410
411\begin{figure}
412\begin{cquote}
413\setlength{\tabcolsep}{15pt}
414\begin{tabular}{@{}ll@{}}
415\begin{cfa}
416int main() {
417        enum(int ) E { BBB = 3, AAA, AA, AB, B };
418        E e;
419
420        for () {
421                try {
422                        @sin | e@;
423                } catch( missing_data * ) {
424                        sout | "missing data";
425                        continue; // try again
426                }
427          if ( eof( sin ) ) break;
428                sout | e | "= " | value( e );
429        }
430}
431\end{cfa}
432&
433\begin{cfa}
434$\rm input$
435BBBABAAAAB
436BBB AAA AA AB B
437
438$\rm output$
439BBB = 3
440AB = 6
441AAA = 4
442AB = 6
443BBB = 3
444AAA = 4
445AA = 5
446AB = 6
447B = 7
448
449\end{cfa}
450\end{tabular}
451\end{cquote}
452\caption{Enumeration I/O}
453\label{f:EnumerationI/O}
454\end{figure}
455
456
457
458\section{Planet Example}
459
460\VRef[Figure]{f:PlanetExample} shows an archetypal enumeration example illustrating most of the \CFA enumeration features.
461@Planet@ is an enumeration of type @MR@.
462Each planet enumerator is initialized to a specific mass/radius, @MR@, value.
463The unnamed enumeration provides the gravitational-constant enumerator @G@.
464Function @surfaceGravity@ uses the @with@ clause to remove @p@ qualification from fields @mass@ and @radius@.
465The program main uses the pseudo function @countof@ to obtain the number of enumerators in @Planet@, and safely converts the random value into a @Planet@ enumerator using @fromInt@.
466The resulting random orbital-body is used in a @choose@ statement.
467The enumerators in the @case@ clause use the enumerator position for testing.
468The prints use @label@ to print an enumerator's name.
469Finally, a loop enumerates through the planets computing the weight on each planet for a given earth mass.
470The print statement does an equality comparison with an enumeration variable and enumerator (@p == MOON@).
471
472\begin{figure}
473\small
474\begin{cfa}
475struct MR { double mass, radius; };                     $\C{// planet definition}$
476enum( @MR@ ) Planet {                                           $\C{// typed enumeration}$
477        //                      mass (kg)   radius (km)
478        MERCURY = { 0.330_E24, 2.4397_E6 },
479        VENUS      = { 4.869_E24, 6.0518_E6 },
480        EARTH       = { 5.976_E24, 6.3781_E6 },
481        MOON        = { 7.346_E22, 1.7380_E6 }, $\C{// not a planet}$
482        MARS         = { 0.642_E24, 3.3972_E6 },
483        JUPITER    = { 1898._E24, 71.492_E6 },
484        SATURN     = { 568.8_E24, 60.268_E6 },
485        URANUS    = { 86.86_E24, 25.559_E6 },
486        NEPTUNE  = { 102.4_E24, 24.746_E6 },
487        PLUTO       = { 1.303_E22, 1.1880_E6 }, $\C{// not a planet}$
488};
489enum( double ) { G = 6.6743_E-11 };                     $\C{// universal gravitational constant (m3 kg-1 s-2)}$
490static double surfaceGravity( Planet p ) @with( p )@ {
491        return G * mass / ( radius @\@ 2 );             $\C{// no qualification, exponentiation}$
492}
493static double surfaceWeight( Planet p, double otherMass ) {
494        return otherMass * surfaceGravity( p );
495}
496int main( int argc, char * argv[] ) {
497        if ( argc != 2 ) @exit@ | "Usage: " | argv[0] | "earth-weight";  // terminate program
498        double earthWeight = convert( argv[1] );
499        double earthMass = earthWeight / surfaceGravity( EARTH );
500        Planet rp = @fromInt@( prng( @countof@( Planet ) ) ); $\C{// select random orbiting body}$
501        @choose( rp )@ {                                                $\C{// implicit breaks}$
502          case MERCURY, VENUS, EARTH, MARS:
503                sout | @rp@ | "is a rocky planet";
504          case JUPITER, SATURN, URANUS, NEPTUNE:
505                sout | rp | "is a gas-giant planet";
506          default:
507                sout | rp | "is not a planet";
508        }
509        for ( @p; Planet@ ) {                                   $\C{// enumerate}$
510                sout | "Your weight on" | ( @p == MOON@ ? "the" : " " ) | p
511                           | "is" | wd( 1,1,  surfaceWeight( p, earthMass ) ) | "kg";
512        }
513}
514$\$$ planet 100
515JUPITER is a gas-giant planet
516Your weight on MERCURY is 37.7 kg
517Your weight on VENUS is 90.5 kg
518Your weight on EARTH is 100.0 kg
519Your weight on the MOON is 16.6 kg
520Your weight on MARS is 37.9 kg
521Your weight on JUPITER is 252.8 kg
522Your weight on SATURN is 106.6 kg
523Your weight on URANUS is 90.5 kg
524Your weight on NEPTUNE is 113.8 kg
525Your weight on PLUTO is 6.3 kg
526\end{cfa}
527\caption{Planet Example}
528\label{f:PlanetExample}
529\end{figure}
Note: See TracBrowser for help on using the repository browser.