1 | \chapter{Related Work} |
---|
2 | \label{s:RelatedWork} |
---|
3 | |
---|
4 | \begin{comment} |
---|
5 | An algebraic data type (ADT) can be viewed as a recursive sum of product types. |
---|
6 | A sum type lists values as members. |
---|
7 | A member in a sum type definition is known as a data constructor. |
---|
8 | For example, C supports sum types union and enumeration (enum). |
---|
9 | An enumeration in C can be viewed as the creation of a list of zero-arity data constructors. |
---|
10 | A union instance holds a value of one of its member types. |
---|
11 | Defining a union does not generate new constructors. |
---|
12 | The definition of member types and their constructors are from the outer lexical scope. |
---|
13 | |
---|
14 | In general, an \Newterm{algebraic data type} (ADT) is a composite type, \ie, a type formed by combining other types. |
---|
15 | Three common classes of algebraic types are \Newterm{array type}, \ie homogeneous types, \Newterm{product type}, \ie heterogeneous tuples and records (structures), and \Newterm{sum type}, \ie tagged product-types (unions). |
---|
16 | Enumerated types are a special case of product/sum types with non-mutable fields, \ie initialized (constructed) once at the type's declaration, possible restricted to compile-time initialization. |
---|
17 | Values of algebraic types are access by subscripting, field qualification, or type (pattern) matching. |
---|
18 | \end{comment} |
---|
19 | |
---|
20 | Enumeration types exist in many popular programming languages, both past and present, \eg Pascal~\cite{Pascal}, Ada~\cite{Ada}, \Csharp~\cite{Csharp}, OCaml~\cite{OCaml} \CC, Go~\cite{Go}, Java~\cite{Java}, Modula-3~\cite{Modula-3}, Rust~\cite{Rust}, Swift~\cite{Swift}, Python~\cite{Python}. |
---|
21 | Among theses languages, there are a large set of overlapping features, but each language has its own unique extensions and restrictions. |
---|
22 | |
---|
23 | \section{Pascal} |
---|
24 | \label{s:Pascal} |
---|
25 | |
---|
26 | Classic Pascal has the \lstinline[language=pascal]{const} declaration binding a name to a constant literal/expression. |
---|
27 | \begin{pascal} |
---|
28 | const one = 0 + 1; Vowels = set of (A,E,I,O,U); NULL = NIL; |
---|
29 | PI = 3.14159; Plus = '+'; Fred = 'Fred'; |
---|
30 | \end{pascal} |
---|
31 | This mechanism is not an enumeration because there is no specific type (pseudo enumeration). |
---|
32 | Hence, there is no notion of a (possibly ordered) set, modulo the \lstinline[language=pascal]{set of} type. |
---|
33 | The type of each constant name (enumerator) is inferred from the constant-expression type. |
---|
34 | |
---|
35 | Free Pascal~\cite[\S~3.1.1]{FreePascal} is a modern, object-oriented version of classic Pascal, with a C-style enumeration type. |
---|
36 | Enumerators must be assigned in ascending numerical order with a constant expression and the range can be non-consecutive. |
---|
37 | \begin{pascal} |
---|
38 | Type EnumType = ( one, two, three, forty @= 40@, fortyone ); |
---|
39 | \end{pascal} |
---|
40 | Pseudo-functions @Pred@ and @Succ@ can only be used if the range is consecutive. |
---|
41 | The underlying type is an implementation-defined integral-type large enough to hold all enumerated values; it does not have to be the smallest possible type. |
---|
42 | The integral size can be explicitly specified using compiler directive @$PACKENUM@~$N$, where $N$ is the number of bytes, \eg: |
---|
43 | \begin{pascal} |
---|
44 | Type @{$\color{red}\$$PACKENUM 1}@ SmallEnum = ( one, two, three ); |
---|
45 | @{$\color{red}\$$PACKENUM 4}@ LargeEnum = ( BigOne, BigTwo, BigThree ); |
---|
46 | Var S : SmallEnum; { 1 byte } |
---|
47 | L : LargeEnum; { 4 bytes} |
---|
48 | \end{pascal} |
---|
49 | |
---|
50 | |
---|
51 | \section{Ada} |
---|
52 | |
---|
53 | An Ada enumeration type is a set of ordered unscoped identifiers (enumerators) bound to \emph{unique} \Newterm{literals}.\footnote{% |
---|
54 | Ada is \emph{case-insensitive} so identifiers may appear in multiple forms and still be the same, \eg \lstinline{Mon}, \lstinline{moN}, and \lstinline{MON} (a questionable design decision).} |
---|
55 | \begin{ada} |
---|
56 | type Week is ( Mon, Tue, Wed, Thu, Fri, Sat, Sun ); -- literals (enumerators) |
---|
57 | \end{ada} |
---|
58 | Object initialization and assignment are restricted to the enumerators of this type. |
---|
59 | While Ada enumerators are unscoped, like C, Ada enumerators are overloadable. |
---|
60 | \begin{ada} |
---|
61 | type RGB is ( @Red@, @Green@, Blue ); |
---|
62 | type Traffic_Light is ( @Red@, Yellow, @Green@ ); |
---|
63 | \end{ada} |
---|
64 | Like \CFA, Ada uses an advanced type-resolution algorithm, including the left-hand side of assignment, to disambiguate among overloaded identifiers. |
---|
65 | \VRef[Figure]{f:AdaEnumeration} shows how ambiguity is handled using a cast, \ie \lstinline[language=ada]{RGB'(Red)}. |
---|
66 | |
---|
67 | \begin{figure} |
---|
68 | \begin{ada} |
---|
69 | with Ada.Text_IO; use Ada.Text_IO; |
---|
70 | procedure test is |
---|
71 | type RGB is ( @Red@, Green, Blue ); |
---|
72 | type Traffic_Light is ( @Red@, Yellow, Green ); -- overload |
---|
73 | procedure @Red@( Colour : RGB ) is begin -- overload |
---|
74 | Put_Line( "Colour is " & RGB'Image( Colour ) ); |
---|
75 | end Red; |
---|
76 | procedure @Red@( TL : Traffic_Light ) is begin -- overload |
---|
77 | Put_Line( "Light is " & Traffic_Light'Image( TL ) ); |
---|
78 | end Red; |
---|
79 | begin |
---|
80 | @Red@( Blue ); -- RGB |
---|
81 | @Red@( Yellow ); -- Traffic_Light |
---|
82 | @Red@( @RGB'(Red)@ ); -- ambiguous without cast |
---|
83 | end test; |
---|
84 | \end{ada} |
---|
85 | \caption{Ada Enumeration Overload Resolution} |
---|
86 | \label{f:AdaEnumeration} |
---|
87 | \end{figure} |
---|
88 | |
---|
89 | Enumerators without initialization are auto-initialized from left to right, starting at zero, incrementing by 1. |
---|
90 | Enumerators with initialization must set \emph{all} enumerators in \emph{ascending} order, \ie there is no auto-initialization. |
---|
91 | \begin{ada} |
---|
92 | type Week is ( Mon, Tue, Wed, Thu, Fri, Sat, Sun ); |
---|
93 | for Week use ( Mon => 0, Tue => 1, Wed => 2, Thu => @10@, Fri => 11, Sat => 14, Sun => 15 ); |
---|
94 | \end{ada} |
---|
95 | The enumeration operators are the equality and relational operators, @=@, @/=@, @<@, @<=@, @=@, @/=@, @>=@, @>@, where the ordering relationship is given implicitly by the sequence of acsending enumerators. |
---|
96 | |
---|
97 | Ada provides an alias mechanism, \lstinline[language=ada]{renames}, for aliasing types, which is useful to shorten package identifiers. |
---|
98 | \begin{ada} |
---|
99 | OtherRed : RGB renames Red; |
---|
100 | \end{ada} |
---|
101 | which suggests a possible \CFA extension to @typedef@. |
---|
102 | \begin{cfa} |
---|
103 | typedef RGB.Red OtherRed; |
---|
104 | \end{cfa} |
---|
105 | |
---|
106 | There are three pairs of inverse enumeration pseudo-functions (attributes): @'Pos@ and @'Val@, @'Enum_Rep@ and @'Enum_Val@, and @'Image@ and @'Value@, |
---|
107 | \begin{cquote} |
---|
108 | \setlength{\tabcolsep}{15pt} |
---|
109 | \begin{tabular}{@{}ll@{}} |
---|
110 | \begin{ada} |
---|
111 | RGB'Pos( Red ) = 0; |
---|
112 | RGB'Enum_Rep( Red ) = 10; |
---|
113 | RGB'Image( Red ) = "RED"; |
---|
114 | \end{ada} |
---|
115 | & |
---|
116 | \begin{ada} |
---|
117 | RGB'Val( 0 ) = Red |
---|
118 | RGB'Enum_Val( 10 ) = Red |
---|
119 | RGB'Value( "Red" ) = Red |
---|
120 | \end{ada} |
---|
121 | \end{tabular} |
---|
122 | \end{cquote} |
---|
123 | These attributes are important for IO. |
---|
124 | An enumeration type @T@ also has the following attributes: @T'First@, @T'Last@, @T'Range@, @T'Pred@, @T'Succ@, @T'Min@, and @T'Max@, producing an intuitive result based on the attribute name. |
---|
125 | |
---|
126 | Ada allows the enumerator label to be a character constant. |
---|
127 | \begin{ada} |
---|
128 | type Operator is ( '+', '-', '*', '/' ); |
---|
129 | \end{ada} |
---|
130 | which is syntactic sugar for the label and not character literals from the predefined type @Character@. |
---|
131 | The purpose is strictly readability using character literals rather than identifiers. |
---|
132 | \begin{ada} |
---|
133 | Op : Operator := '+'; |
---|
134 | if Op = '+' or else Op = '-' then ... ; |
---|
135 | elsif Op = '*' or else Op = '/' then ... ; end if; |
---|
136 | \end{ada} |
---|
137 | Interestingly, arrays of character enumerators can be treated as strings. |
---|
138 | \begin{ada} |
---|
139 | Ops : array( 0..3 ) of Operator; |
---|
140 | Ops := @"+-*/"@; -- string assignment to array elements |
---|
141 | Ops := @"+-" & "*/"@; -- string concatenation and assignment |
---|
142 | \end{ada} |
---|
143 | Ada's @Character@ type is defined as a character enumeration across all Latin-1 characters. |
---|
144 | |
---|
145 | Ada's boolean type is also a special enumeration, which can be used in conditions. |
---|
146 | \begin{ada} |
---|
147 | type Boolean is (False, True); -- False / True not keywords |
---|
148 | @Flag@ : Boolean; |
---|
149 | if @Flag@ then ... -- conditional |
---|
150 | \end{ada} |
---|
151 | Since only types derived from @Boolean@ can be a conditional, @Boolean@ is essentially a builtin type. |
---|
152 | |
---|
153 | Ada provides \emph{consecutive} subtyping of an enumeration using \lstinline[language=ada]{range}. |
---|
154 | \begin{ada} |
---|
155 | type Week is ( Mon, Tue, Wed, Thu, Fri, Sat, Sun ); |
---|
156 | subtype Weekday is Week @range Mon .. Fri@; |
---|
157 | subtype Weekend is Week @range Sat .. Sun@; |
---|
158 | Day : Week; |
---|
159 | \end{ada} |
---|
160 | Hence, the ordering of the enumerators is crucial to provide the necessary ranges. |
---|
161 | |
---|
162 | An enumeration type can be used in the Ada \lstinline[language=ada]{case} (all enumerators must appear or a default) or iterating constructs. |
---|
163 | \begin{cquote} |
---|
164 | \setlength{\tabcolsep}{15pt} |
---|
165 | \begin{tabular}{@{}ll@{}} |
---|
166 | \begin{ada} |
---|
167 | case Day is |
---|
168 | when @Mon .. Fri@ => ... ; |
---|
169 | when @Sat .. Sun@ => ... ; |
---|
170 | end case; |
---|
171 | \end{ada} |
---|
172 | & |
---|
173 | \begin{ada} |
---|
174 | case Day is |
---|
175 | when @Weekday@ => ... ; -- subtype ranges |
---|
176 | when @Weekend@ => ... ; |
---|
177 | end case; |
---|
178 | \end{ada} |
---|
179 | \end{tabular} |
---|
180 | \end{cquote} |
---|
181 | |
---|
182 | \begin{cquote} |
---|
183 | \setlength{\tabcolsep}{12pt} |
---|
184 | \begin{tabular}{@{}lll@{}} |
---|
185 | \begin{ada} |
---|
186 | for Day in @Mon .. Sun@ loop |
---|
187 | ... |
---|
188 | end loop; |
---|
189 | \end{ada} |
---|
190 | & |
---|
191 | \begin{ada} |
---|
192 | for Day in @Weekday@ loop |
---|
193 | ... |
---|
194 | end loop; |
---|
195 | \end{ada} |
---|
196 | & |
---|
197 | \begin{ada} |
---|
198 | for Day in @Weekend@ loop |
---|
199 | ... |
---|
200 | end loop; |
---|
201 | \end{ada} |
---|
202 | \end{tabular} |
---|
203 | \end{cquote} |
---|
204 | |
---|
205 | An enumeration type can be used as an array dimension and subscript. |
---|
206 | \begin{ada} |
---|
207 | Lunch : array( @Week@ ) of Time; |
---|
208 | for Day in Week loop |
---|
209 | Lunch( @Day@ ) := ... ; -- set lunch time |
---|
210 | end loop; |
---|
211 | \end{ada} |
---|
212 | |
---|
213 | |
---|
214 | \section{\CC} |
---|
215 | \label{s:C++RelatedWork} |
---|
216 | |
---|
217 | \CC has the equivalent of Pascal typed @const@ declarations \see{\VRef{s:Pascal}}, with static and dynamic initialization. |
---|
218 | \begin{c++} |
---|
219 | const auto one = 0 + 1; $\C{// static initialization}$ |
---|
220 | const auto NULL = nullptr; |
---|
221 | const auto PI = 3.14159; |
---|
222 | const auto Plus = '+'; |
---|
223 | const auto Fred = "Fred"; |
---|
224 | const auto Mon = 0, Tue = Mon + 1, Wed = Tue + 1, Thu = Wed + 1, Fri = Thu + 1, |
---|
225 | Sat = Fri + 1, Sun = Sat + 1; |
---|
226 | int sa[Sun]; |
---|
227 | const auto r = random(); $\C{// dynamic initialization}$ |
---|
228 | int da[r]; $\C{// VLA}$ |
---|
229 | \end{c++} |
---|
230 | Statically initialized identifiers may appear in any constant-expression context, \eg @case@. |
---|
231 | Dynamically intialized identifiers may appear as array dimensions in @g++@, which allows variable-sized arrays. |
---|
232 | Interestingly, global \CC @const@ declarations are implicitly marked @static@ (@r@ rather than @R@). |
---|
233 | \begin{c++} |
---|
234 | $\$$ nm test.o |
---|
235 | 0000000000000018 @r@ Mon |
---|
236 | \end{c++} |
---|
237 | |
---|
238 | \CC enumeration is largely backwards compatible with C, so it inherited C's enumerations. |
---|
239 | However, the following non-backwards compatible changes are made. |
---|
240 | |
---|
241 | \begin{cquote} |
---|
242 | 7.2 Change: \CC objects of enumeration type can only be assigned values of the same enumeration type. |
---|
243 | In C, objects of enumeration type can be assigned values of any integral type. \\ |
---|
244 | Example: |
---|
245 | \begin{c++} |
---|
246 | enum color { red, blue, green }; |
---|
247 | color c = 1; $\C{// valid C, invalid C++}$ |
---|
248 | \end{c++} |
---|
249 | \textbf{Rationale}: The type-safe nature of \CC. \\ |
---|
250 | \textbf{Effect on original feature}: Deletion of semantically well-defined feature. \\ |
---|
251 | \textbf{Difficulty of converting}: Syntactic transformation. (The type error produced by the assignment can be automatically corrected by applying an explicit cast.) \\ |
---|
252 | \textbf{How widely used}: Common. |
---|
253 | \end{cquote} |
---|
254 | |
---|
255 | \begin{cquote} |
---|
256 | 7.2 Change: In \CC, the type of an enumerator is its enumeration. |
---|
257 | In C, the type of an enumerator is @int@. \\ |
---|
258 | Example: |
---|
259 | \begin{c++} |
---|
260 | enum e { A }; |
---|
261 | sizeof(A) == sizeof(int) $\C{// in C}$ |
---|
262 | sizeof(A) == sizeof(e) $\C{// in C++}$ |
---|
263 | /* and sizeof(int) is not necessary equal to sizeof(e) */ |
---|
264 | \end{c++} |
---|
265 | \textbf{Rationale}: In \CC, an enumeration is a distinct type. \\ |
---|
266 | \textbf{Effect on original feature}: Change to semantics of well-defined feature. \\ |
---|
267 | \textbf{Difficulty of converting}: Semantic transformation. \\ |
---|
268 | \textbf{How widely used}: Seldom. The only time this affects existing C code is when the size of an enumerator is taken. |
---|
269 | Taking the size of an enumerator is not a common C coding practice. |
---|
270 | \end{cquote} |
---|
271 | |
---|
272 | Hence, the values in a \CC enumeration can only be its enumerators (without a cast). |
---|
273 | While the storage size of an enumerator is up to the compiler, there is still an implicit cast to @int@. |
---|
274 | \begin{c++} |
---|
275 | enum E { A, B, C }; |
---|
276 | E e = A; |
---|
277 | int i = A; i = e; $\C{// implicit casts to int}$ |
---|
278 | \end{c++} |
---|
279 | \CC{11} added a scoped enumeration, \lstinline[language=c++]{enum class} (or \lstinline[language=c++]{enum struct}), where the enumerators are accessed using type qualification. |
---|
280 | \begin{c++} |
---|
281 | enum class E { A, B, C }; |
---|
282 | E e = @E::@A; $\C{// qualified enumerator}$ |
---|
283 | e = B; $\C{// error: B not in scope}$ |
---|
284 | \end{c++} |
---|
285 | \CC{20} supports explicit unscoping with a \lstinline[language=c++]{using enum} declaration. |
---|
286 | \begin{c++} |
---|
287 | enum class E { A, B, C }; |
---|
288 | @using enum E;@ |
---|
289 | E e = A; e = B; $\C{// direct access}$ |
---|
290 | \end{c++} |
---|
291 | \CC{11} added the ability to explicitly declare the underlying \emph{integral} type for \lstinline[language=c++]{enum class}. |
---|
292 | \begin{c++} |
---|
293 | enum class RGB @: long@ { Red, Green, Blue }; |
---|
294 | enum class rgb @: char@ { Red = 'r', Green = 'g', Blue = 'b' }; |
---|
295 | enum class srgb @: signed char@ { Red = -1, Green = 0, Blue = 1 }; |
---|
296 | \end{c++} |
---|
297 | There is no implicit conversion from the \lstinline[language=c++]{enum class} type to its declared type. |
---|
298 | \begin{c++} |
---|
299 | rgb crgb = rgb::Red; |
---|
300 | char ch = rgb::Red; ch = crgb; $\C{// error}$ |
---|
301 | \end{c++} |
---|
302 | Finally, enumerations can be used in the @switch@ statement but there is no mechanism to iterate through an enumeration. |
---|
303 | An enumeration type cannot declare an array dimension but can be used as a subscript. |
---|
304 | There is no mechanism to subtype or inherit from enumerations. |
---|
305 | |
---|
306 | |
---|
307 | \section{C\raisebox{-0.7ex}{\LARGE$^\sharp$}\xspace} % latex bug: cannot use \relsize{2} so use \LARGE |
---|
308 | \label{s:Csharp} |
---|
309 | |
---|
310 | % https://www.tutorialsteacher.com/codeeditor?cid=cs-mk8Ojx |
---|
311 | |
---|
312 | \Csharp is a dynamically-typed programming-language with a scoped, integral enumeration-type similar to the C/\CC enumeration. |
---|
313 | \begin{csharp} |
---|
314 | enum Weekday : byte { Mon, Tue, Wed, Thu@ = 10@, Fri, Sat, Sun@,@ }; |
---|
315 | \end{csharp} |
---|
316 | The default underlying type is @int@, with auto-incrementing, implicit/explicit initialization, terminator comma, and optional integral typing (default @int@). |
---|
317 | A method cannot be defined in an enumeration type. |
---|
318 | As well, there is an explicit bidirectional conversion between an enumeration and its integral type, and an implicit conversion to the enumerator label in display contexts. |
---|
319 | \begin{csharp} |
---|
320 | int day = (int)Weekday.Fri; $\C{// day == 10}$ |
---|
321 | Weekday weekday = (Weekdays)42; $\C{// weekday == 42, logically invalid}$ |
---|
322 | Console.WriteLine( Weekday.Fri ); $\C{// print Fri}$ |
---|
323 | string mon = Weekday.Mon.ToString(); $\C{// mon == "Mon"}$ |
---|
324 | \end{csharp} |
---|
325 | |
---|
326 | The @Enum.GetValues@ pseudo-method retrieves an array of the enumeration constants for looping over an enumeration type or variable (expensive operation). |
---|
327 | \begin{csharp} |
---|
328 | foreach ( Weekday constant in @Enum.GetValues@( typeof(Weekday) ) ) { |
---|
329 | Console.WriteLine( constant + " " + (int)constant ); // label, position |
---|
330 | } |
---|
331 | \end{csharp} |
---|
332 | |
---|
333 | The @Flags@ attribute creates a bit-flags enumeration, allowing bitwise operators @&@, @|@, @~@ (complement), @^@ (xor). |
---|
334 | \begin{csharp} |
---|
335 | @[Flags]@ public enum Weekday { |
---|
336 | None = 0x0, Mon = 0x1, Tue = 0x2, Wed = 0x4, |
---|
337 | Thu = 0x8, Fri = 0x10, Sat = 0x20, Sun = 0x40, |
---|
338 | Weekend = @Sat | Sun@, |
---|
339 | Weekdays = @Mon | Tue | Wed | Thu | Fri@ |
---|
340 | } |
---|
341 | Weekday meetings = @Weekday.Mon | Weekday.Wed@; // 0x5 |
---|
342 | \end{csharp} |
---|
343 | |
---|
344 | \VRef[Figure]{CsharpFreeVersusClass} shows an enumeration with free routines for manipulation, and embedding the enumeration and operations into an enumeration class. |
---|
345 | The key observation is that an enumeration class is just a structuring mechanism without any additional semantics. |
---|
346 | |
---|
347 | % https://learn.microsoft.com/en-us/dotnet/api/system.enum?view=net-8.0 |
---|
348 | |
---|
349 | \begin{figure} |
---|
350 | \centering |
---|
351 | \begin{tabular}{@{}l|l@{}} |
---|
352 | \multicolumn{1}{@{}c|}{non-object oriented} & \multicolumn{1}{c@{}}{object oriented} \\ |
---|
353 | \hline |
---|
354 | \begin{csharp} |
---|
355 | public class Program { |
---|
356 | |
---|
357 | enum Weekday { |
---|
358 | Mon, Tue, Wed, Thu, Fri, Sat, Sun }; |
---|
359 | |
---|
360 | static bool isWeekday( Weekday wd ) { |
---|
361 | return wd <= Weekday.Fri; |
---|
362 | } |
---|
363 | static bool isWeekend( Weekday wd ) { |
---|
364 | return Weekday.Sat <= wd; |
---|
365 | } |
---|
366 | |
---|
367 | |
---|
368 | public static void Main() { |
---|
369 | Weekday day = Weekday.Sat; |
---|
370 | |
---|
371 | Console.WriteLine( isWeekday( day ) ); |
---|
372 | Console.WriteLine( isWeekend( day ) ); |
---|
373 | } |
---|
374 | } |
---|
375 | \end{csharp} |
---|
376 | & |
---|
377 | \begin{csharp} |
---|
378 | public class Program { |
---|
379 | public @class@ WeekDay : Enumeration { |
---|
380 | public enum Day { |
---|
381 | Mon, Tue, Wed, Thu, Fri, Sat, Sun }; |
---|
382 | public enum Day2 : Day { |
---|
383 | XXX, YYY }; |
---|
384 | Day day; |
---|
385 | public bool isWeekday() { |
---|
386 | return day <= Day.Fri; |
---|
387 | } |
---|
388 | public bool isWeekend() { |
---|
389 | return day > Day.Fri; |
---|
390 | } |
---|
391 | public WeekDay( Day d ) { day = d; } |
---|
392 | } |
---|
393 | public static void Main() { |
---|
394 | WeekDay cday = new |
---|
395 | WeekDay( WeekDay.Day.Sat ); |
---|
396 | Console.WriteLine( cday.isWeekday() ); |
---|
397 | Console.WriteLine( cday.isWeekend() ); |
---|
398 | } |
---|
399 | } |
---|
400 | \end{csharp} |
---|
401 | \end{tabular} |
---|
402 | \caption{\Csharp: Free Routine Versus Class Enumeration} |
---|
403 | \label{CsharpFreeVersusClass} |
---|
404 | \end{figure} |
---|
405 | |
---|
406 | |
---|
407 | \section{Golang} |
---|
408 | |
---|
409 | Golang provides pseudo-enumeration similar to classic Pascal \lstinline[language=pascal]{const}, binding a name to a constant literal/expression. |
---|
410 | \begin{Go} |
---|
411 | const ( R = 0; G; B ) $\C{// implicit: 0 0 0}$ |
---|
412 | const ( Fred = "Fred"; Mary = "Mary"; Jane = "Jane" ) $\C{// explicit: Fred Mary Jane}$ |
---|
413 | const ( S = 0; T; USA = "USA"; U; V = 3.1; W ) $\C{// type change, implicit/explicit: 0 0 USA USA 3.1 3.1}$ |
---|
414 | \end{Go} |
---|
415 | Constant identifiers are unscoped and must be unique (no overloading). |
---|
416 | The first enumerator \emph{must} be explicitly initialized; |
---|
417 | subsequent enumerators can be implicitly or explicitly initialized. |
---|
418 | Implicit initialization is the previous (predecessor) enumerator value. |
---|
419 | |
---|
420 | Auto-incrementing is supported by the keyword \lstinline[language=Go]{iota}, available only in the \lstinline[language=Go]{const} declaration. |
---|
421 | The \lstinline[language=Go]{iota} is a \emph{per \lstinline[language=golang]{const} declaration} integer counter, starting at zero and implicitly incremented by one for each \lstinline[language=golang]{const} identifier (enumerator). |
---|
422 | \begin{Go} |
---|
423 | const ( R = @iota@; G; B ) $\C{// implicit: 0 1 2}$ |
---|
424 | const ( C = @iota + B + 1@; G; Y ) $\C{// implicit: 3 4 5}$ |
---|
425 | \end{Go} |
---|
426 | An underscore \lstinline[language=golang]{const} identifier advances \lstinline[language=Go]{iota}. |
---|
427 | \begin{Go} |
---|
428 | const ( O1 = iota + 1; @_@; O3; @_@; O5 ) // 1, 3, 5 |
---|
429 | \end{Go} |
---|
430 | Auto-incrementing stops after an explicit initialization. |
---|
431 | \begin{Go} |
---|
432 | const ( Mon = iota; Tue; Wed; // 0, 1, 2 |
---|
433 | @Thu = 10@; Fri; Sat; Sun ) // 10, 10, 10, 10 |
---|
434 | \end{Go} |
---|
435 | Auto-incrementing can be restarted with an expression containing \emph{one} \lstinline[language=Go]{iota}. |
---|
436 | \begin{Go} |
---|
437 | const ( V1 = iota; V2; @V3 = 7;@ V4 = @iota@; V5 ) // 0 1 7 3 4 |
---|
438 | const ( Mon = iota; Tue; Wed; // 0, 1, 2 |
---|
439 | @Thu = 10;@ Fri = @iota - Wed + Thu - 1@; Sat; Sun ) // 10, 11, 12, 13 |
---|
440 | \end{Go} |
---|
441 | Note, \lstinline[language=Go]{iota} is advanced for an explicitly initialized enumerator, like the underscore @_@ identifier. |
---|
442 | |
---|
443 | Basic switch and looping are possible. |
---|
444 | \begin{cquote} |
---|
445 | \setlength{\tabcolsep}{15pt} |
---|
446 | \begin{tabular}{@{}ll@{}} |
---|
447 | \begin{Go} |
---|
448 | day := Mon; |
---|
449 | switch day { |
---|
450 | case Mon, Tue, Wed, Thu, Fri: |
---|
451 | fmt.Println( "weekday" ); |
---|
452 | case Sat, Sun: |
---|
453 | fmt.Println( "weekend" ); |
---|
454 | } |
---|
455 | \end{Go} |
---|
456 | & |
---|
457 | \begin{Go} |
---|
458 | |
---|
459 | for i := Mon; i <= Sun; i += 1 { |
---|
460 | fmt.Println( i ) |
---|
461 | } |
---|
462 | |
---|
463 | |
---|
464 | |
---|
465 | \end{Go} |
---|
466 | \end{tabular} |
---|
467 | \end{cquote} |
---|
468 | However, the loop prints the values from 0 to 13 because there is no actual enumeration. |
---|
469 | |
---|
470 | |
---|
471 | \section{Java} |
---|
472 | |
---|
473 | Every enumeration in Java is an enumeration class. |
---|
474 | For a basic enumeration |
---|
475 | \begin{Java} |
---|
476 | enum Weekday { Mon, Tue, Wed, Thu, Fri, Sat, Sun }; |
---|
477 | Weekday day = Weekday.Sat; |
---|
478 | \end{Java} |
---|
479 | the scoped enumerators are an ordered list of @final@ methods of type integer, ordered left to right starting at 0, increasing by 1. |
---|
480 | The value of an enumeration instance is restricted to the enumeration's enumerators. |
---|
481 | There is an implicit @int@ variable in the enumeration used to store the value of an enumeration instance. |
---|
482 | The position (ordinal) and label are accessible, where the value is the same as the position. |
---|
483 | \begin{Java} |
---|
484 | System.out.println( day.!ordinal()! + " " + day.!name()! ); // 5 Sat |
---|
485 | \end{Java} |
---|
486 | There is an inverse function @valueOf@ from string to enumerator. |
---|
487 | \begin{Java} |
---|
488 | day = Weekday.valueOf( "Wed" ); |
---|
489 | \end{Java} |
---|
490 | There are no implicit conversions to/from an enumerator and its underlying type. |
---|
491 | Like \Csharp, \VRef[Figure]{f:JavaFreeVersusClass} shows the same example for an enumeration with free routines for manipulation, and embedding the enumeration and operations into an enumeration class. |
---|
492 | |
---|
493 | \begin{figure} |
---|
494 | \centering |
---|
495 | \begin{tabular}{@{}l|l@{}} |
---|
496 | \multicolumn{1}{@{}c|}{non-object oriented} & \multicolumn{1}{c@{}}{object oriented} \\ |
---|
497 | \hline |
---|
498 | \begin{Java} |
---|
499 | enum Weekday !{! |
---|
500 | Mon, Tue, Wed, Thu, Fri, Sat, Sun !}!; |
---|
501 | |
---|
502 | static boolean isWeekday( Weekday wd ) { |
---|
503 | return wd.ordinal() <= Weekday.Fri.ordinal(); |
---|
504 | } |
---|
505 | static boolean isWeekend( Weekday wd ) { |
---|
506 | return Weekday.Fri.ordinal() < wd.ordinal(); |
---|
507 | } |
---|
508 | |
---|
509 | public static void main( String[] args ) { |
---|
510 | Weekday day = Weekday.Sat; |
---|
511 | System.out.println( isWeekday( day ) ); |
---|
512 | System.out.println( isWeekend( day ) ); |
---|
513 | } |
---|
514 | \end{Java} |
---|
515 | & |
---|
516 | \begin{Java} |
---|
517 | enum Weekday !{! |
---|
518 | Mon, Tue, Wed, Thu, Fri, Sat, Sun; |
---|
519 | |
---|
520 | public boolean isWeekday() { |
---|
521 | return ordinal() <= Weekday.Fri.ordinal(); |
---|
522 | } |
---|
523 | public boolean isWeekend() { |
---|
524 | return Weekday.Fri.ordinal() < ordinal(); |
---|
525 | } |
---|
526 | !}! |
---|
527 | public static void main( String[] args ) { |
---|
528 | WeekDay day = WeekDay.Sat; |
---|
529 | System.out.println( day.isWeekday() ); |
---|
530 | System.out.println( day.isWeekend() ); |
---|
531 | } |
---|
532 | \end{Java} |
---|
533 | \end{tabular} |
---|
534 | \caption{Java: Free Routine Versus Class Enumeration} |
---|
535 | \label{f:JavaFreeVersusClass} |
---|
536 | \end{figure} |
---|
537 | |
---|
538 | To explicitly assign enumerator values and/or use a non-@int@ enumeration type (any Java type may be used), the enumeration must specify an explicit type in the enumeration class and a constructor. |
---|
539 | \begin{Java} |
---|
540 | enum Weekday { |
---|
541 | Mon!(1)!, Tue!(2)!, Wed!(3)!, Thu!(4)!, Fri!(5)!, Sat!(6)!, Sun!(7)!; // must appear first |
---|
542 | private !long! day; $\C{// underlying enumeration type}$ |
---|
543 | private Weekday( !long! d ) { day = d; } $\C{// used to initialize enumerators}$ |
---|
544 | }; |
---|
545 | Weekday day = Weekday.Sat; |
---|
546 | \end{Java} |
---|
547 | If an enumerator initialization is a runtime expression, the expression is executed once at the point the enumeration is declaraed. |
---|
548 | |
---|
549 | The position, value, and label are accessible. |
---|
550 | \begin{Java} |
---|
551 | System.out.println( !day.ordinal()! + " " + !day.day! + " " + !day.name()! ); // 5 6 Sat |
---|
552 | \end{Java} |
---|
553 | The constructor is private so only initialization or assignment can be used to set an enumeration, which ensures only corresponding enumerator values are allowed. |
---|
554 | |
---|
555 | An enumeration can appear in a @switch@ statement, but no ranges. |
---|
556 | \begin{Java} |
---|
557 | switch ( day ) { |
---|
558 | case Mon: case Tue: case Wed: case Thu: case Fri: |
---|
559 | System.out.println( "weekday" ); |
---|
560 | break; |
---|
561 | case Sat: case Sun: |
---|
562 | System.out.println( "weekend" ); |
---|
563 | break; |
---|
564 | } |
---|
565 | \end{Java} |
---|
566 | Like \Csharp, looping over an enumeration is done using method @values@, which returns the array of enumerator values (expensive operation). |
---|
567 | \begin{Java} |
---|
568 | for ( Weekday iday : Weekday.values() ) { |
---|
569 | System.out.print( iday.ordinal() + iday.day + " " + iday.name() + ", " ); |
---|
570 | } |
---|
571 | 0 1 Mon, 1 2 Tue, 2 3 Wed, 3 4 Thu, 4 5 Fri, 5 6 Sat, 6 7 Sun, |
---|
572 | \end{Java} |
---|
573 | |
---|
574 | As well, Java provides an @EnumSet@ where the underlying type is an efficient set of bits, one per enumeration \see{\Csharp \lstinline{Flags}, \VRef{s:Csharp}}, providing (logical) operations on groups of enumerators. |
---|
575 | There is also a specialized version of @HashMap@ with enumerator keys, which has performance benefits. |
---|
576 | |
---|
577 | Enumeration inheritence is disallowed because an enumeration is @final@. |
---|
578 | |
---|
579 | |
---|
580 | |
---|
581 | \section{Modula-3} |
---|
582 | |
---|
583 | |
---|
584 | |
---|
585 | \section{Rust} |
---|
586 | % https://doc.rust-lang.org/reference/items/enumerations.html |
---|
587 | |
---|
588 | Rust provides a scoped enumeration based on variant types. |
---|
589 | % An enumeration, also referred to as an enum, is a simultaneous definition of a nominal enumerated type as well as a set of constructors, that can be used to create or pattern-match values of the corresponding enumerated type. |
---|
590 | An enumeration without constructors is called field-less. |
---|
591 | \begin{rust} |
---|
592 | enum Week { Mon, Tues, Wed, Thu, Fri, Sat, Sun@,@ } |
---|
593 | let mut week: Week = Week::Mon; |
---|
594 | week = Week::Fri; |
---|
595 | \end{rust} |
---|
596 | A field-less enumeration with only unit variants is called unit-only. |
---|
597 | \begin{rust} |
---|
598 | enum Week { Mon = 0, Tues = 1, Wed = 2, Thu = 3, Fri = 4, Sat = 5, Sun = 6 } |
---|
599 | \end{rust} |
---|
600 | Enum constructors can have either named or unnamed fields: |
---|
601 | \begin{rust} |
---|
602 | enum Animal { |
---|
603 | Dog( String, f64 ), |
---|
604 | Cat{ name: String, weight: f64 }, |
---|
605 | } |
---|
606 | let mut a: Animal = Animal::Dog("Cocoa".to_string(), 37.2); |
---|
607 | a = Animal::Cat { name: "Spotty".to_string(), weight: 2.7 }; |
---|
608 | \end{rust} |
---|
609 | Here, @Dog@ is an @enum@ variant, whereas @Cat@ is a struct-like variant. |
---|
610 | |
---|
611 | Each @enum@ type has an implicit integer tag (discriminant), with a unique value for each variant type. |
---|
612 | Like a C enumeration, the tag values for the variant types start at 0 with auto incrementing. |
---|
613 | The tag is re-purposed for enumeration by allowing it to be explicitly set, and auto incrmenting continues from that value. |
---|
614 | \begin{cquote} |
---|
615 | \sf\setlength{\tabcolsep}{3pt} |
---|
616 | \begin{tabular}{rcccccccr} |
---|
617 | @enum@ Week \{ & Mon, & Tue, & Wed = 2, & Thu = 10, & Fri, & Sat = 5, & Sun & \}; \\ |
---|
618 | \rm tags & 0 & 1 & 2 & 10 & 11 & 5 & 6 & \\ |
---|
619 | \end{tabular} |
---|
620 | \end{cquote} |
---|
621 | In general, the tag can only be read as an opaque reference for comparison. |
---|
622 | \begin{rust} |
---|
623 | if mem::discriminant(&week) == mem::discriminant(&Week::Mon) ... |
---|
624 | \end{rust} |
---|
625 | If the enumeration is unit-only, or field-less with no explicit discriminants and where only unit variants are explicit, then the discriminant is accessible with a numeric cast. |
---|
626 | \begin{rust} |
---|
627 | if week as isize == Week::Mon as isize ... |
---|
628 | \end{rust} |
---|
629 | |
---|
630 | |
---|
631 | \section{Swift} |
---|
632 | |
---|
633 | % https://www.programiz.com/swift/online-compiler |
---|
634 | |
---|
635 | A Swift enumeration provides a heterogenous set of enumerators, like a tagged @union@, where the field name is the enumerator and its list of type parameters form its type. |
---|
636 | \begin{swift} |
---|
637 | enum Many { |
---|
638 | case Mon, Tue, Wed, Thu, Fri, Sat, Sun // basic enumerator |
---|
639 | case code( String ) // string enumerator |
---|
640 | case tuple( Int, Int, Int ) // tuple enumerator |
---|
641 | }; |
---|
642 | var day = Many.Sat; // qualification to resolve type |
---|
643 | print( day ); |
---|
644 | day = .Wed // no qualification after type resolved |
---|
645 | print( day ); |
---|
646 | day = .code( "ABC" ); |
---|
647 | print( day ); |
---|
648 | day = .tuple( 1, 2, 3 ); |
---|
649 | print( day ); |
---|
650 | |
---|
651 | Sat |
---|
652 | Wed |
---|
653 | code("ABC") |
---|
654 | tuple(1, 2, 3) |
---|
655 | \end{swift} |
---|
656 | |
---|
657 | |
---|
658 | An enumeration defines a common type for a group of related values and enables you to work with those values in a type-safe way within your code. |
---|
659 | |
---|
660 | If you are familiar with C, you will know that C enumerations assign related names to a set of integer values. |
---|
661 | Enumerations in Swift are much more flexible, and don't have to provide a value for each case of the enumeration. |
---|
662 | If a value (known as a raw value) is provided for each enumeration case, the value can be a string, a character, or a value of any integer or floating-point type. |
---|
663 | |
---|
664 | Alternatively, enumeration cases can specify associated values of any type to be stored along with each different case value, much as unions or variants do in other languages. |
---|
665 | You can define a common set of related cases as part of one enumeration, each of which has a different set of values of appropriate types associated with it. |
---|
666 | |
---|
667 | Enumerations in Swift are first-class types in their own right. |
---|
668 | They adopt many features traditionally supported only by classes, such as computed properties to provide additional information about the enumeration's current value, and instance methods to provide functionality related to the values the enumeration represents. |
---|
669 | Enumerations can also define initializers to provide an initial case value; |
---|
670 | can be extended to expand their functionality beyond their original implementation; and can conform to protocols to provide standard functionality. |
---|
671 | |
---|
672 | For more about these capabilities, see Properties, Methods, Initialization, Extensions, and Protocols. |
---|
673 | |
---|
674 | \paragraph{Enumeration Syntax} |
---|
675 | |
---|
676 | |
---|
677 | Note: |
---|
678 | Swift enumeration cases don't have an integer value set by default, unlike languages like C and Objective-C. |
---|
679 | In the CompassPoint example above, @north@, @south@, @east@ and @west@ don't implicitly equal 0, 1, 2 and 3. |
---|
680 | Instead, the different enumeration cases are values in their own right, with an explicitly defined type of CompassPoint. |
---|
681 | |
---|
682 | Multiple cases can appear on a single line, separated by commas: |
---|
683 | \begin{swift} |
---|
684 | enum Planet { |
---|
685 | case mercury, venus, earth, mars, jupiter, saturn, uranus, neptune |
---|
686 | } |
---|
687 | \end{swift} |
---|
688 | Each enumeration definition defines a new type. |
---|
689 | Like other types in Swift, their names (such as @CompassPoint@ and @Planet@) start with a capital letter. |
---|
690 | Give enumeration types singular rather than plural names, so that they read as self-evident: |
---|
691 | \begin{swift} |
---|
692 | var directionToHead = CompassPoint.west |
---|
693 | \end{swift} |
---|
694 | The type of @directionToHead@ is inferred when it's initialized with one of the possible values of @CompassPoint@. |
---|
695 | Once @directionToHead@ is declared as a @CompassPoint@, you can set it to a different @CompassPoint@ value using a shorter dot syntax: |
---|
696 | \begin{swift} |
---|
697 | directionToHead = .east |
---|
698 | \end{swift} |
---|
699 | The type of @directionToHead@ is already known, and so you can drop the type when setting its value. |
---|
700 | This makes for highly readable code when working with explicitly typed enumeration values. |
---|
701 | |
---|
702 | \paragraph{Matching Enumeration Values with a Switch Statement} |
---|
703 | |
---|
704 | You can match individual enumeration values with a switch statement: |
---|
705 | \begin{swift} |
---|
706 | directionToHead = .south |
---|
707 | switch directionToHead { |
---|
708 | case .north: |
---|
709 | print("Lots of planets have a north") |
---|
710 | case .south: |
---|
711 | print("Watch out for penguins") |
---|
712 | case .east: |
---|
713 | print("Where the sun rises") |
---|
714 | case .west: |
---|
715 | print("Where the skies are blue") |
---|
716 | } |
---|
717 | // Prints "Watch out for penguins" |
---|
718 | \end{swift} |
---|
719 | You can read this code as: |
---|
720 | \begin{quote} |
---|
721 | "Consider the value of directionToHead. |
---|
722 | In the case where it equals @.north@, print "Lots of planets have a north". |
---|
723 | In the case where it equals @.south@, print "Watch out for penguins"." |
---|
724 | |
---|
725 | ...and so on. |
---|
726 | \end{quote} |
---|
727 | As described in Control Flow, a switch statement must be exhaustive when considering an enumeration's cases. |
---|
728 | If the case for @.west@ is omitted, this code doesn't compile, because it doesn't consider the complete list of @CompassPoint@ cases. |
---|
729 | Requiring exhaustiveness ensures that enumeration cases aren't accidentally omitted. |
---|
730 | |
---|
731 | When it isn't appropriate to provide a case for every enumeration case, you can provide a default case to cover any cases that aren't addressed explicitly: |
---|
732 | \begin{swift} |
---|
733 | let somePlanet = Planet.earth |
---|
734 | switch somePlanet { |
---|
735 | case .earth: |
---|
736 | print("Mostly harmless") |
---|
737 | default: |
---|
738 | print("Not a safe place for humans") |
---|
739 | } |
---|
740 | // Prints "Mostly harmless" |
---|
741 | \end{swift} |
---|
742 | |
---|
743 | \paragraph{Iterating over Enumeration Cases} |
---|
744 | |
---|
745 | For some enumerations, it's useful to have a collection of all of that enumeration's cases. |
---|
746 | You enable this by writing @CaseIterable@ after the enumeration's name. |
---|
747 | Swift exposes a collection of all the cases as an allCases property of the enumeration type. |
---|
748 | Here's an example: |
---|
749 | \begin{swift} |
---|
750 | enum Beverage: CaseIterable { |
---|
751 | case coffee, tea, juice |
---|
752 | } |
---|
753 | let numberOfChoices = Beverage.allCases.count |
---|
754 | print("\(numberOfChoices) beverages available") |
---|
755 | // Prints "3 beverages available" |
---|
756 | \end{swift} |
---|
757 | In the example above, you write @Beverage.allCases@ to access a collection that contains all of the cases of the @Beverage@ enumeration. |
---|
758 | You can use @allCases@ like any other collection -- the collection's elements are instances of the enumeration type, so in this case they're Beverage values. |
---|
759 | The example above counts how many cases there are, and the example below uses a for-in loop to iterate over all the cases. |
---|
760 | \begin{swift} |
---|
761 | for beverage in Beverage.allCases { |
---|
762 | print(beverage) |
---|
763 | } |
---|
764 | // coffee |
---|
765 | // tea |
---|
766 | // juice |
---|
767 | \end{swift} |
---|
768 | The syntax used in the examples above marks the enumeration as conforming to the @CaseIterable@ protocol. |
---|
769 | For information about protocols, see Protocols. |
---|
770 | |
---|
771 | \paragraph{Associated Values} |
---|
772 | The examples in the previous section show how the cases of an enumeration are a defined (and typed) value in their own right. |
---|
773 | You can set a constant or variable to Planet.earth, and check for this value later. |
---|
774 | However, it's sometimes useful to be able to store values of other types alongside these case values. |
---|
775 | This additional information is called an associated value, and it varies each time you use that case as a value in your code. |
---|
776 | |
---|
777 | You can define Swift enumerations to store associated values of any given type, and the value types can be different for each case of the enumeration if needed. |
---|
778 | Enumerations similar to these are known as discriminated unions, tagged unions, or variants in other programming languages. |
---|
779 | |
---|
780 | For example, suppose an inventory tracking system needs to track products by two different types of barcode. |
---|
781 | Some products are labeled with 1D barcodes in UPC format, which uses the numbers 0 to 9. |
---|
782 | Each barcode has a number system digit, followed by five manufacturer code digits and five product code digits. |
---|
783 | These are followed by a check digit to verify that the code has been scanned correctly: |
---|
784 | |
---|
785 | Other products are labeled with 2D barcodes in QR code format, which can use any ISO 8859-1 character and can encode a string up to 2,953 characters long: |
---|
786 | |
---|
787 | It's convenient for an inventory tracking system to store UPC barcodes as a tuple of four integers, and QR code barcodes as a string of any length. |
---|
788 | |
---|
789 | In Swift, an enumeration to define product barcodes of either type might look like this: |
---|
790 | \begin{swift} |
---|
791 | enum Barcode { |
---|
792 | case upc(Int, Int, Int, Int) |
---|
793 | case qrCode(String) |
---|
794 | } |
---|
795 | \end{swift} |
---|
796 | This can be read as: |
---|
797 | \begin{quote} |
---|
798 | "Define an enumeration type called Barcode, which can take either a value of upc with an associated value of type @(Int, Int, Int, Int)@, or a value of @qrCode@ with an associated value of type @String@." |
---|
799 | \end{quote} |
---|
800 | This definition doesn't provide any actual @Int@ or @String@ values -- it just defines the type of associated values that Barcode constants and variables can store when they're equal to @Barcode.upc@ or @Barcode.qrCode@. |
---|
801 | |
---|
802 | You can then create new barcodes using either type: |
---|
803 | \begin{swift} |
---|
804 | var productBarcode = Barcode.upc(8, 85909, 51226, 3) |
---|
805 | \end{swift} |
---|
806 | This example creates a new variable called @productBarcode@ and assigns it a value of @Barcode.upc@ with an associated tuple value of @(8, 85909, 51226, 3)@. |
---|
807 | |
---|
808 | You can assign the same product a different type of barcode: |
---|
809 | \begin{swift} |
---|
810 | productBarcode = .qrCode("ABCDEFGHIJKLMNOP") |
---|
811 | \end{swift} |
---|
812 | At this point, the original @Barcode.upc@ and its integer values are replaced by the new @Barcode.qrCode@ and its string value. |
---|
813 | Constants and variables of type Barcode can store either a @.upc@ or a @.qrCode@ (together with their associated values), but they can store only one of them at any given time. |
---|
814 | |
---|
815 | You can check the different barcode types using a switch statement, similar to the example in Matching Enumeration Values with a Switch Statement. |
---|
816 | This time, however, the associated values are extracted as part of the switch statement. |
---|
817 | You extract each associated value as a constant (with the let prefix) or a variable (with the var prefix) for use within the switch case's body: |
---|
818 | \begin{swift} |
---|
819 | switch productBarcode { |
---|
820 | case .upc(let numberSystem, let manufacturer, let product, let check): |
---|
821 | print("UPC: \(numberSystem), \(manufacturer), \(product), \(check).") |
---|
822 | case .qrCode(let productCode): |
---|
823 | print("QR code: \(productCode).") |
---|
824 | } |
---|
825 | // Prints "QR code: ABCDEFGHIJKLMNOP." |
---|
826 | \end{swift} |
---|
827 | If all of the associated values for an enumeration case are extracted as constants, or if all are extracted as variables, you can place a single let or var annotation before the case name, for brevity: |
---|
828 | \begin{swift} |
---|
829 | switch productBarcode { |
---|
830 | case let .upc(numberSystem, manufacturer, product, check): |
---|
831 | print("UPC : \(numberSystem), \(manufacturer), \(product), \(check).") |
---|
832 | case let .qrCode(productCode): |
---|
833 | print("QR code: \(productCode).") |
---|
834 | } |
---|
835 | // Prints "QR code: ABCDEFGHIJKLMNOP." |
---|
836 | \end{swift} |
---|
837 | |
---|
838 | \paragraph{Raw Values} |
---|
839 | |
---|
840 | The barcode example in Associated Values shows how cases of an enumeration can declare that they store associated values of different types. |
---|
841 | As an alternative to associated values, enumeration cases can come prepopulated with default values (called raw values), which are all of the same type. |
---|
842 | |
---|
843 | Here's an example that stores raw ASCII values alongside named enumeration cases: |
---|
844 | \begin{swift} |
---|
845 | enum ASCIIControlCharacter: Character { |
---|
846 | case tab = "\t" |
---|
847 | case lineFeed = "\n" |
---|
848 | case carriageReturn = "\r" |
---|
849 | } |
---|
850 | \end{swift} |
---|
851 | Here, the raw values for an enumeration called ASCIIControlCharacter are defined to be of type Character, and are set to some of the more common ASCII control characters. |
---|
852 | Character values are described in Strings and Characters. |
---|
853 | |
---|
854 | Raw values can be strings, characters, or any of the integer or floating-point number types. |
---|
855 | Each raw value must be unique within its enumeration declaration. |
---|
856 | |
---|
857 | Note |
---|
858 | |
---|
859 | Raw values are not the same as associated values. |
---|
860 | Raw values are set to prepopulated values when you first define the enumeration in your code, like the three ASCII codes above. |
---|
861 | The raw value for a particular enumeration case is always the same. |
---|
862 | Associated values are set when you create a new constant or variable based on one of the enumeration's cases, and can be different each time you do so. |
---|
863 | Implicitly Assigned Raw Values |
---|
864 | |
---|
865 | When you're working with enumerations that store integer or string raw values, you don't have to explicitly assign a raw value for each case. |
---|
866 | When you don't, Swift automatically assigns the values for you. |
---|
867 | |
---|
868 | For example, when integers are used for raw values, the implicit value for each case is one more than the previous case. |
---|
869 | If the first case doesn't have a value set, its value is 0. |
---|
870 | |
---|
871 | The enumeration below is a refinement of the earlier Planet enumeration, with integer raw values to represent each planet's order from the sun: |
---|
872 | |
---|
873 | \begin{swift} |
---|
874 | enum Planet: Int { |
---|
875 | case mercury = 1, venus, earth, mars, jupiter, saturn, uranus, neptune |
---|
876 | } |
---|
877 | \end{swift} |
---|
878 | In the example above, Planet.mercury has an explicit raw value of 1, Planet.venus has an implicit raw value of 2, and so on. |
---|
879 | |
---|
880 | When strings are used for raw values, the implicit value for each case is the text of that case's name. |
---|
881 | |
---|
882 | The enumeration below is a refinement of the earlier CompassPoint enumeration, with string raw values to represent each direction's name: |
---|
883 | \begin{swift} |
---|
884 | enum CompassPoint: String { |
---|
885 | case north, south, east, west |
---|
886 | } |
---|
887 | \end{swift} |
---|
888 | In the example above, CompassPoint.south has an implicit raw value of "south", and so on. |
---|
889 | |
---|
890 | You access the raw value of an enumeration case with its rawValue property: |
---|
891 | \begin{swift} |
---|
892 | let earthsOrder = Planet.earth.rawValue |
---|
893 | // earthsOrder is 3 |
---|
894 | |
---|
895 | let sunsetDirection = CompassPoint.west.rawValue |
---|
896 | // sunsetDirection is "west" |
---|
897 | \end{swift} |
---|
898 | |
---|
899 | \paragraph{Initializing from a Raw Value} |
---|
900 | |
---|
901 | If you define an enumeration with a raw-value type, the enumeration automatically receives an initializer that takes a value of the raw value's type (as a parameter called rawValue) and returns either an enumeration case or nil. |
---|
902 | You can use this initializer to try to create a new instance of the enumeration. |
---|
903 | |
---|
904 | This example identifies Uranus from its raw value of 7: |
---|
905 | \begin{swift} |
---|
906 | let possiblePlanet = Planet(rawValue: 7) |
---|
907 | // possiblePlanet is of type Planet? and equals Planet.uranus |
---|
908 | \end{swift} |
---|
909 | Not all possible Int values will find a matching planet, however. |
---|
910 | Because of this, the raw value initializer always returns an optional enumeration case. |
---|
911 | In the example above, possiblePlanet is of type Planet?, or "optional Planet." |
---|
912 | Note |
---|
913 | |
---|
914 | The raw value initializer is a failable initializer, because not every raw value will return an enumeration case. |
---|
915 | For more information, see Failable Initializers. |
---|
916 | |
---|
917 | If you try to find a planet with a position of 11, the optional Planet value returned by the raw value initializer will be nil: |
---|
918 | \begin{swift} |
---|
919 | let positionToFind = 11 |
---|
920 | if let somePlanet = Planet(rawValue: positionToFind) { |
---|
921 | switch somePlanet { |
---|
922 | case .earth: |
---|
923 | print("Mostly harmless") |
---|
924 | default: |
---|
925 | print("Not a safe place for humans") |
---|
926 | } |
---|
927 | } else { |
---|
928 | print("There isn't a planet at position \(positionToFind)") |
---|
929 | } |
---|
930 | // Prints "There isn't a planet at position 11" |
---|
931 | \end{swift} |
---|
932 | This example uses optional binding to try to access a planet with a raw value of 11. |
---|
933 | The statement if let somePlanet = Planet(rawValue: 11) creates an optional Planet, and sets somePlanet to the value of that optional Planet if it can be retrieved. |
---|
934 | In this case, it isn't possible to retrieve a planet with a position of 11, and so the else branch is executed instead. |
---|
935 | |
---|
936 | \paragraph{Recursive Enumerations} |
---|
937 | |
---|
938 | A recursive enumeration is an enumeration that has another instance of the enumeration as the associated value for one or more of the enumeration cases. |
---|
939 | You indicate that an enumeration case is recursive by writing indirect before it, which tells the compiler to insert the necessary layer of indirection. |
---|
940 | |
---|
941 | For example, here is an enumeration that stores simple arithmetic expressions: |
---|
942 | \begin{swift} |
---|
943 | enum ArithmeticExpression { |
---|
944 | case number(Int) |
---|
945 | indirect case addition(ArithmeticExpression, ArithmeticExpression) |
---|
946 | indirect case multiplication(ArithmeticExpression, ArithmeticExpression) |
---|
947 | } |
---|
948 | \end{swift} |
---|
949 | You can also write indirect before the beginning of the enumeration to enable indirection for all of the enumeration's cases that have an associated value: |
---|
950 | \begin{swift} |
---|
951 | indirect enum ArithmeticExpression { |
---|
952 | case number(Int) |
---|
953 | case addition(ArithmeticExpression, ArithmeticExpression) |
---|
954 | case multiplication(ArithmeticExpression, ArithmeticExpression) |
---|
955 | } |
---|
956 | \end{swift} |
---|
957 | This enumeration can store three kinds of arithmetic expressions: a plain number, the addition of two expressions, and the multiplication of two expressions. |
---|
958 | The addition and multiplication cases have associated values that are also arithmetic expressions -- these associated values make it possible to nest expressions. |
---|
959 | For example, the expression (5 + 4) * 2 has a number on the right-hand side of the multiplication and another expression on the left-hand side of the multiplication. |
---|
960 | Because the data is nested, the enumeration used to store the data also needs to support nesting -- this means the enumeration needs to be recursive. |
---|
961 | The code below shows the ArithmeticExpression recursive enumeration being created for (5 + 4) * 2: |
---|
962 | \begin{swift} |
---|
963 | let five = ArithmeticExpression.number(5) |
---|
964 | let four = ArithmeticExpression.number(4) |
---|
965 | let sum = ArithmeticExpression.addition(five, four) |
---|
966 | let product = ArithmeticExpression.multiplication(sum, ArithmeticExpression.number(2)) |
---|
967 | \end{swift} |
---|
968 | A recursive function is a straightforward way to work with data that has a recursive structure. |
---|
969 | For example, here's a function that evaluates an arithmetic expression: |
---|
970 | \begin{swift} |
---|
971 | func evaluate(_ expression: ArithmeticExpression) -> Int { |
---|
972 | switch expression { |
---|
973 | case let .number(value): |
---|
974 | return value |
---|
975 | case let .addition(left, right): |
---|
976 | return evaluate(left) + evaluate(right) |
---|
977 | case let .multiplication(left, right): |
---|
978 | return evaluate(left) * evaluate(right) |
---|
979 | } |
---|
980 | } |
---|
981 | |
---|
982 | print(evaluate(product)) |
---|
983 | // Prints "18" |
---|
984 | \end{swift} |
---|
985 | This function evaluates a plain number by simply returning the associated value. |
---|
986 | It evaluates an addition or multiplication by evaluating the expression on the left-hand side, evaluating the expression on the right-hand side, and then adding them or multiplying them. |
---|
987 | |
---|
988 | |
---|
989 | \section{Python 3.13} |
---|
990 | % https://docs.python.org/3/howto/enum.html |
---|
991 | |
---|
992 | Python is a dynamically-typed reflexive programming language with multiple versions, and hence, it is possible to extend existing or build new language features within the language. |
---|
993 | As a result, discussing Python enumerations is a moving target, because if a features does not exist, if can often be created with varying levels of complexity. |
---|
994 | Nevertheless, an attempt has been made to discuss core enumeration features that come with Python 3.13. |
---|
995 | |
---|
996 | A Python enumeration type is a set of ordered scoped identifiers (enumerators) bound to \emph{unique} values. |
---|
997 | An enumeration is not a basic type; |
---|
998 | it is a @class@ inheriting from the @Enum@ class, where the enumerators must be explicitly initialized, \eg: |
---|
999 | \begin{python} |
---|
1000 | class Week(@Enum@): Mon = 1; Tue = 2; Wed = 3; Thu = 4; Fri = 5; Sat = 6; Sun = 7 |
---|
1001 | \end{python} |
---|
1002 | and/or explicitly auto initialized, \eg: |
---|
1003 | \begin{python} |
---|
1004 | class Week(Enum): Mon = 1; Tue = 2; Wed = 3; Thu = 10; Fri = @auto()@; Sat = 4; Sun = @auto()@ |
---|
1005 | \end{python} |
---|
1006 | where @auto@ increments by 1 from the previous enumerator value. |
---|
1007 | Object initialization and assignment are restricted to the enumerators of this type. |
---|
1008 | An enumerator initialized with same value is an alias and invisible at the enumeration level, \ie the alias it substituted for its aliasee. |
---|
1009 | \begin{python} |
---|
1010 | class Week(Enum): Mon = 1; Tue = 2; Wed = 3; Thu = 10; Fri = @10@; Sat = @10@; Sun = @10@ |
---|
1011 | \end{python} |
---|
1012 | Here, the enumeration has only 4 enumerators and 3 aliases. |
---|
1013 | An alias is only visible by dropping down to the @class@ level and asking for class members. |
---|
1014 | @Enum@ only supports equality comparison between enumerator values; |
---|
1015 | the extended class @OrderedEnum@ adds relational operators @<@, @<=@, @>@, and @>=@. |
---|
1016 | |
---|
1017 | There are bidirectional enumeration pseudo-functions for label and value, but there is no concept of access using ordering (position). |
---|
1018 | \begin{cquote} |
---|
1019 | \setlength{\tabcolsep}{15pt} |
---|
1020 | \begin{tabular}{@{}ll@{}} |
---|
1021 | \begin{python} |
---|
1022 | Week.Thu.value == 10; |
---|
1023 | Week.Thu.name == 'Thu'; |
---|
1024 | \end{python} |
---|
1025 | & |
---|
1026 | \begin{python} |
---|
1027 | Week( 10 ) == Thu |
---|
1028 | Week['Thu'].value = 10 |
---|
1029 | \end{python} |
---|
1030 | \end{tabular} |
---|
1031 | \end{cquote} |
---|
1032 | |
---|
1033 | As an enumeration is a \lstinline[language=python]{class}, its own methods. |
---|
1034 | \begin{python} |
---|
1035 | class Week(Enum): |
---|
1036 | Mon = 1; Tue = 2; Wed = 3; Thu = 4; Fri = 5; Sat = 6; Sun = 7 |
---|
1037 | $\\@$classmethod |
---|
1038 | def today(cls, date): |
---|
1039 | return cls(date.isoweekday()) |
---|
1040 | print( "today:", Week.today(date.today())) |
---|
1041 | today: Week.Mon |
---|
1042 | \end{python} |
---|
1043 | The method @today@ retrieves the day of the week and uses it as an index to print out the corresponding label of @Week@. |
---|
1044 | |
---|
1045 | @Flag@ allows combining several members into a single variable: |
---|
1046 | \begin{python} |
---|
1047 | print( repr(WeekF.Sat | WeekF.Sun) ) |
---|
1048 | <WeekF.Sun|Sat: 96> |
---|
1049 | \end{python} |
---|
1050 | You can even iterate over a @Flag@ variable: |
---|
1051 | \begin{python} |
---|
1052 | for day in weekend: |
---|
1053 | print(day) |
---|
1054 | WeekF.Sat |
---|
1055 | WeekF.Sun |
---|
1056 | \end{python} |
---|
1057 | Okay, let's get some chores set up: |
---|
1058 | \begin{python} |
---|
1059 | >>> chores_for_ethan = { |
---|
1060 | ... 'feed the cat': Week.MONDAY | Week.WEDNESDAY | Week.FRIDAY, |
---|
1061 | ... 'do the dishes': Week.TUESDAY | Week.THURSDAY, |
---|
1062 | ... 'answer SO questions': Week.SATURDAY, |
---|
1063 | ... } |
---|
1064 | \end{python} |
---|
1065 | And a function to display the chores for a given day: |
---|
1066 | \begin{python} |
---|
1067 | >>> def show_chores(chores, day): |
---|
1068 | ... for chore, days in chores.items(): |
---|
1069 | ... if day in days: |
---|
1070 | ... print(chore) |
---|
1071 | >>> show_chores(chores_for_ethan, Week.SATURDAY) |
---|
1072 | answer SO questions |
---|
1073 | \end{python} |
---|
1074 | Auto incrmenet for @Flag@ is by powers of 2. |
---|
1075 | \begin{python} |
---|
1076 | class WeekF(Flag): Mon = auto(); Tue = auto(); Wed = auto(); Thu = auto(); Fri = auto(); \ |
---|
1077 | Sat = auto(); Sun = auto(); Weekend = Sat | Sun |
---|
1078 | for d in WeekF: |
---|
1079 | print( f"{d.name}: {d.value}", end=" ") |
---|
1080 | Mon: 1 Tue: 2 Wed: 4 Thu: 8 Fri: 16 Sat: 32 Sun: 64 WeekA.Weekend |
---|
1081 | \end{python} |
---|
1082 | |
---|
1083 | \subsection{Programmatic access to enumeration members and their attributes} |
---|
1084 | |
---|
1085 | Sometimes it's useful to access members in enumerations programmatically (i.e. situations where @Color.RED@ won't do because the exact color is not known at program-writing time). |
---|
1086 | @Enum@ allows such access: |
---|
1087 | \begin{python} |
---|
1088 | print(RGB(1), RGB(3), ) |
---|
1089 | RGB.RED RGB.GREEN |
---|
1090 | \end{python} |
---|
1091 | If you want to access enum members by name, use item access: |
---|
1092 | \begin{python} |
---|
1093 | print( RGBa['RED'], RGBa['GREEN'] ) |
---|
1094 | RGB.RED RGB.GREEN |
---|
1095 | \end{python} |
---|
1096 | If you have an enum member and need its name or value: |
---|
1097 | \begin{python} |
---|
1098 | member = RGBa.RED |
---|
1099 | print( f"{member.name} {member.value}" ) |
---|
1100 | RED 1 |
---|
1101 | \end{python} |
---|
1102 | |
---|
1103 | |
---|
1104 | \subsection{Ensuring unique enumeration values} |
---|
1105 | |
---|
1106 | By default, enumerations allow multiple names as aliases for the same value. |
---|
1107 | When this behavior isn't desired, you can use the @unique()@ decorator: |
---|
1108 | \begin{python} |
---|
1109 | from enum import Enum, unique |
---|
1110 | $@$unique |
---|
1111 | class DupVal(Enum): ONE = 1; TWO = 2; THREE = 3; FOUR = 3 |
---|
1112 | ValueError: duplicate values found in <enum 'Mistake'>: FOUR -> THREE |
---|
1113 | \end{python} |
---|
1114 | |
---|
1115 | \subsection{Using automatic values} |
---|
1116 | |
---|
1117 | If the exact value is unimportant you can use @auto@: |
---|
1118 | \begin{python} |
---|
1119 | from enum import Enum, auto |
---|
1120 | class RGBa(Enum): RED = auto(); BLUE = auto(); GREEN = auto() |
---|
1121 | \end{python} |
---|
1122 | (Like Golang @iota@.) |
---|
1123 | The values are chosen by @_generate_next_value_()@, which can be overridden: |
---|
1124 | \begin{python} |
---|
1125 | >>> class AutoName(Enum): |
---|
1126 | ... $@$staticmethod |
---|
1127 | ... def _generate_next_value_(name, start, count, last_values): |
---|
1128 | ... return name |
---|
1129 | ... |
---|
1130 | >>> class Ordinal(AutoName): |
---|
1131 | ... NORTH = auto() |
---|
1132 | ... SOUTH = auto() |
---|
1133 | ... EAST = auto() |
---|
1134 | ... WEST = auto() |
---|
1135 | ... |
---|
1136 | >>> [member.value for member in Ordinal] |
---|
1137 | ['NORTH', 'SOUTH', 'EAST', 'WEST'] |
---|
1138 | \end{python} |
---|
1139 | Note The @_generate_next_value_()@ method must be defined before any members. |
---|
1140 | |
---|
1141 | \subsection{Iteration} |
---|
1142 | |
---|
1143 | Iterating over the members of an enum does not provide the aliases: |
---|
1144 | \begin{python} |
---|
1145 | >>> list(Shape) |
---|
1146 | [<Shape.SQUARE: 2>, <Shape.DIAMOND: 1>, <Shape.CIRCLE: 3>] |
---|
1147 | >>> list(Week) |
---|
1148 | [<Week.MONDAY: 1>, <Week.TUESDAY: 2>, <Week.WEDNESDAY: 4>, <Week.THURSDAY: 8>, |
---|
1149 | <Week.FRIDAY: 16>, <Week.SATURDAY: 32>, <Week.SUNDAY: 64>] |
---|
1150 | \end{python} |
---|
1151 | Note that the aliases @Shape.ALIAS_FOR_SQUARE@ and @Week.WEEKEND@ aren't shown. |
---|
1152 | |
---|
1153 | The special attribute @__members__@ is a read-only ordered mapping of names to members. |
---|
1154 | It includes all names defined in the enumeration, including the aliases: |
---|
1155 | \begin{python} |
---|
1156 | >>> for name, member in Shape.__members__.items(): |
---|
1157 | ... name, member |
---|
1158 | ... |
---|
1159 | ('SQUARE', <Shape.SQUARE: 2>) |
---|
1160 | ('DIAMOND', <Shape.DIAMOND: 1>) |
---|
1161 | ('CIRCLE', <Shape.CIRCLE: 3>) |
---|
1162 | ('ALIAS_FOR_SQUARE', <Shape.SQUARE: 2>) |
---|
1163 | \end{python} |
---|
1164 | The @__members__@ attribute can be used for detailed programmatic access to the enumeration members. |
---|
1165 | For example, finding all the aliases: |
---|
1166 | \begin{python} |
---|
1167 | >>> [name for name, member in Shape.__members__.items() if member.name != name] |
---|
1168 | ['ALIAS_FOR_SQUARE'] |
---|
1169 | \end{python} |
---|
1170 | Note: Aliases for flags include values with multiple flags set, such as 3, and no flags set, i.e. 0. |
---|
1171 | |
---|
1172 | \subsection{Comparisons} |
---|
1173 | |
---|
1174 | Enumeration members are compared by identity: |
---|
1175 | \begin{python} |
---|
1176 | >>> Color.RED is Color.RED |
---|
1177 | True |
---|
1178 | >>> Color.RED is Color.BLUE |
---|
1179 | False |
---|
1180 | >>> Color.RED is not Color.BLUE |
---|
1181 | True |
---|
1182 | \end{python} |
---|
1183 | Ordered comparisons between enumeration values are not supported. |
---|
1184 | Enum members are not integers (but see @IntEnum@ below): |
---|
1185 | \begin{python} |
---|
1186 | >>> Color.RED < Color.BLUE |
---|
1187 | Traceback (most recent call last): |
---|
1188 | File "<stdin>", line 1, in <module> |
---|
1189 | TypeError: '<' not supported between instances of 'Color' and 'Color' |
---|
1190 | \end{python} |
---|
1191 | Equality comparisons are defined though: |
---|
1192 | \begin{python} |
---|
1193 | >>> Color.BLUE == Color.RED |
---|
1194 | False |
---|
1195 | >>> Color.BLUE != Color.RED |
---|
1196 | True |
---|
1197 | >>> Color.BLUE == Color.BLUE |
---|
1198 | True |
---|
1199 | \end{python} |
---|
1200 | Comparisons against non-enumeration values will always compare not equal (again, @IntEnum@ was explicitly designed to behave differently, see below): |
---|
1201 | \begin{python} |
---|
1202 | >>> Color.BLUE == 2 |
---|
1203 | False |
---|
1204 | \end{python} |
---|
1205 | |
---|
1206 | Warning: It is possible to reload modules -- if a reloaded module contains enums, they will be recreated, and the new members may not compare identical/equal to the original members. |
---|
1207 | |
---|
1208 | \subsection{Allowed members and attributes of enumerations} |
---|
1209 | |
---|
1210 | Most of the examples above use integers for enumeration values. |
---|
1211 | Using integers is short and handy (and provided by default by the Functional API), but not strictly enforced. |
---|
1212 | In the vast majority of use-cases, one doesn't care what the actual value of an enumeration is. |
---|
1213 | But if the value is important, enumerations can have arbitrary values. |
---|
1214 | |
---|
1215 | Enumerations are Python classes, and can have methods and special methods as usual. If we have this enumeration: |
---|
1216 | \begin{python} |
---|
1217 | >>> class Mood(Enum): |
---|
1218 | ... FUNKY = 1 |
---|
1219 | ... HAPPY = 3 |
---|
1220 | ... |
---|
1221 | ... def describe(self): |
---|
1222 | ... # self is the member here |
---|
1223 | ... return self.name, self.value |
---|
1224 | ... |
---|
1225 | ... def __str__(self): |
---|
1226 | ... return 'my custom str! {0}'.format(self.value) |
---|
1227 | ... |
---|
1228 | ... $@$classmethod |
---|
1229 | ... |
---|
1230 | ... def favorite_mood(cls): |
---|
1231 | ... # cls here is the enumeration |
---|
1232 | ... return cls.HAPPY |
---|
1233 | ... |
---|
1234 | \end{python} |
---|
1235 | Then: |
---|
1236 | \begin{python} |
---|
1237 | >>> Mood.favorite_mood() |
---|
1238 | <Mood.HAPPY: 3> |
---|
1239 | >>> Mood.HAPPY.describe() |
---|
1240 | ('HAPPY', 3) |
---|
1241 | >>> str(Mood.FUNKY) |
---|
1242 | 'my custom str! 1' |
---|
1243 | \end{python} |
---|
1244 | The rules for what is allowed are as follows: names that start and end with a single underscore are reserved by enum and cannot be used; |
---|
1245 | all other attributes defined within an enumeration will become members of this enumeration, with the exception of special methods (@__str__()@, @__add__()@, etc.), descriptors (methods are also descriptors), and variable names listed in @_ignore_@. |
---|
1246 | |
---|
1247 | Note: if your enumeration defines @__new__()@ and/or @__init__()@, any value(s) given to the enum member will be passed into those methods. |
---|
1248 | See Planet for an example. |
---|
1249 | |
---|
1250 | Note: The @__new__()@ method, if defined, is used during creation of the Enum members; |
---|
1251 | it is then replaced by Enum's @__new__()@ which is used after class creation for lookup of existing members. |
---|
1252 | See When to use @__new__()@ vs. @__init__()@ for more details. |
---|
1253 | |
---|
1254 | \subsection{Restricted Enum subclassing} |
---|
1255 | |
---|
1256 | A new @Enum@ class must have one base enum class, up to one concrete data type, and as many object-based mixin classes as needed. |
---|
1257 | The order of these base classes is: |
---|
1258 | \begin{python} |
---|
1259 | class EnumName([mix-in, ...,] [data-type,] base-enum): |
---|
1260 | pass |
---|
1261 | \end{python} |
---|
1262 | Also, subclassing an enumeration is allowed only if the enumeration does not define any members. |
---|
1263 | So this is forbidden: |
---|
1264 | \begin{python} |
---|
1265 | >>> class MoreColor(Color): |
---|
1266 | ... PINK = 17 |
---|
1267 | ... |
---|
1268 | Traceback (most recent call last): |
---|
1269 | ... |
---|
1270 | TypeError: <enum 'MoreColor'> cannot extend <enum 'Color'> |
---|
1271 | \end{python} |
---|
1272 | But this is allowed: |
---|
1273 | \begin{python} |
---|
1274 | >>> class Foo(Enum): |
---|
1275 | ... def some_behavior(self): |
---|
1276 | ... pass |
---|
1277 | ... |
---|
1278 | >>> class Bar(Foo): |
---|
1279 | ... HAPPY = 1 |
---|
1280 | ... SAD = 2 |
---|
1281 | ... |
---|
1282 | \end{python} |
---|
1283 | Allowing subclassing of enums that define members would lead to a violation of some important invariants of types and instances. |
---|
1284 | On the other hand, it makes sense to allow sharing some common behavior between a group of enumerations. (See OrderedEnum for an example.) |
---|
1285 | |
---|
1286 | \subsection{Dataclass support} |
---|
1287 | |
---|
1288 | When inheriting from a @dataclass@, the @__repr__()@ omits the inherited class' name. |
---|
1289 | For example: |
---|
1290 | \begin{python} |
---|
1291 | >>> from dataclasses import dataclass, field |
---|
1292 | >>> $@$dataclass |
---|
1293 | ... class CreatureDataMixin: |
---|
1294 | ... size: str |
---|
1295 | ... legs: int |
---|
1296 | ... tail: bool = field(repr=False, default=True) |
---|
1297 | ... |
---|
1298 | >>> class Creature(CreatureDataMixin, Enum): |
---|
1299 | ... BEETLE = 'small', 6 |
---|
1300 | ... DOG = 'medium', 4 |
---|
1301 | ... |
---|
1302 | >>> Creature.DOG |
---|
1303 | <Creature.DOG: size='medium', legs=4> |
---|
1304 | \end{python} |
---|
1305 | Use the @dataclass()@ argument repr=False to use the standard @repr()@. |
---|
1306 | |
---|
1307 | Changed in version 3.12: Only the dataclass fields are shown in the value area, not the dataclass' name. |
---|
1308 | |
---|
1309 | \subsection{Pickling} |
---|
1310 | |
---|
1311 | Enumerations can be pickled and unpickled: |
---|
1312 | \begin{python} |
---|
1313 | >>> from test.test_enum import Fruit |
---|
1314 | >>> from pickle import dumps, loads |
---|
1315 | >>> Fruit.TOMATO is loads(dumps(Fruit.TOMATO)) |
---|
1316 | True |
---|
1317 | \end{python} |
---|
1318 | The usual restrictions for pickling apply: picklable enums must be defined in the top level of a module, since unpickling requires them to be importable from that module. |
---|
1319 | |
---|
1320 | Note: With pickle protocol version 4 it is possible to easily pickle enums nested in other classes. |
---|
1321 | |
---|
1322 | It is possible to modify how enum members are pickled/unpickled by defining @__reduce_ex__()@ in the enumeration class. |
---|
1323 | The default method is by-value, but enums with complicated values may want to use by-name: |
---|
1324 | \begin{python} |
---|
1325 | >>> import enum |
---|
1326 | >>> class MyEnum(enum.Enum): |
---|
1327 | ... __reduce_ex__ = enum.pickle_by_enum_name |
---|
1328 | \end{python} |
---|
1329 | Note: Using by-name for flags is not recommended, as unnamed aliases will not unpickle. |
---|
1330 | |
---|
1331 | \subsection{Functional API} |
---|
1332 | |
---|
1333 | The @Enum@ class is callable, providing the following functional API: |
---|
1334 | \begin{python} |
---|
1335 | >>> Animal = Enum('Animal', 'ANT BEE CAT DOG') |
---|
1336 | >>> Animal |
---|
1337 | <enum 'Animal'> |
---|
1338 | >>> Animal.ANT |
---|
1339 | <Animal.ANT: 1> |
---|
1340 | >>> list(Animal) |
---|
1341 | [<Animal.ANT: 1>, <Animal.BEE: 2>, <Animal.CAT: 3>, <Animal.DOG: 4>] |
---|
1342 | \end{python} |
---|
1343 | The semantics of this API resemble @namedtuple@. |
---|
1344 | The first argument of the call to @Enum@ is the name of the enumeration. |
---|
1345 | |
---|
1346 | The second argument is the source of enumeration member names. |
---|
1347 | It can be a whitespace-separated string of names, a sequence of names, a sequence of 2-tuples with key/value pairs, or a mapping (e.g. dictionary) of names to values. |
---|
1348 | The last two options enable assigning arbitrary values to enumerations; |
---|
1349 | the others auto-assign increasing integers starting with 1 (use the @start@ parameter to specify a different starting value). |
---|
1350 | A new class derived from @Enum@ is returned. |
---|
1351 | In other words, the above assignment to Animal is equivalent to: |
---|
1352 | \begin{python} |
---|
1353 | >>> class Animal(Enum): |
---|
1354 | ... ANT = 1 |
---|
1355 | ... BEE = 2 |
---|
1356 | ... CAT = 3 |
---|
1357 | ... DOG = 4 |
---|
1358 | ... |
---|
1359 | \end{python} |
---|
1360 | The reason for defaulting to 1 as the starting number and not 0 is that 0 is @False@ in a boolean sense, but by default enum members all evaluate to @True@. |
---|
1361 | |
---|
1362 | Pickling enums created with the functional API can be tricky as frame stack implementation details are used to try and figure out which module the enumeration is being created in (e.g. it will fail if you use a utility function in a separate module, and also may not work on IronPython or Jython). |
---|
1363 | The solution is to specify the module name explicitly as follows: |
---|
1364 | \begin{python} |
---|
1365 | >>> Animal = Enum('Animal', 'ANT BEE CAT DOG', module=__name__) |
---|
1366 | \end{python} |
---|
1367 | Warning: If module is not supplied, and @Enum@ cannot determine what it is, the new @Enum@ members will not be unpicklable; to keep errors closer to the source, pickling will be disabled. |
---|
1368 | |
---|
1369 | The new pickle protocol 4 also, in some circumstances, relies on @__qualname__@ being set to the location where pickle will be able to find the class. |
---|
1370 | For example, if the class was made available in class SomeData in the global scope: |
---|
1371 | \begin{python} |
---|
1372 | >>> Animal = Enum('Animal', 'ANT BEE CAT DOG', qualname='SomeData.Animal') |
---|
1373 | \end{python} |
---|
1374 | The complete signature is: |
---|
1375 | \begin{python} |
---|
1376 | Enum( |
---|
1377 | value='NewEnumName', |
---|
1378 | names=<...>, |
---|
1379 | *, |
---|
1380 | module='...', |
---|
1381 | qualname='...', |
---|
1382 | type=<mixed-in class>, |
---|
1383 | start=1, |
---|
1384 | ) |
---|
1385 | \end{python} |
---|
1386 | \begin{itemize} |
---|
1387 | \item |
---|
1388 | @value@: What the new enum class will record as its name. |
---|
1389 | \item |
---|
1390 | @names@: The enum members. |
---|
1391 | This can be a whitespace- or comma-separated string (values will start at 1 unless otherwise specified): |
---|
1392 | \begin{python} |
---|
1393 | 'RED GREEN BLUE' | 'RED,GREEN,BLUE' | 'RED, GREEN, BLUE' |
---|
1394 | \end{python} |
---|
1395 | or an iterator of names: |
---|
1396 | \begin{python} |
---|
1397 | ['RED', 'GREEN', 'BLUE'] |
---|
1398 | \end{python} |
---|
1399 | or an iterator of (name, value) pairs: |
---|
1400 | \begin{python} |
---|
1401 | [('CYAN', 4), ('MAGENTA', 5), ('YELLOW', 6)] |
---|
1402 | \end{python} |
---|
1403 | or a mapping: |
---|
1404 | \begin{python} |
---|
1405 | {'CHARTREUSE': 7, 'SEA_GREEN': 11, 'ROSEMARY': 42} |
---|
1406 | \end{python} |
---|
1407 | \item |
---|
1408 | module: name of module where new enum class can be found. |
---|
1409 | \item |
---|
1410 | @qualname@: where in module new enum class can be found. |
---|
1411 | \item |
---|
1412 | @type@: type to mix in to new enum class. |
---|
1413 | \item |
---|
1414 | @start@: number to start counting at if only names are passed in. |
---|
1415 | \end{itemize} |
---|
1416 | Changed in version 3.5: The start parameter was added. |
---|
1417 | |
---|
1418 | \subsection{Derived Enumerations} |
---|
1419 | |
---|
1420 | \subsection{IntEnum} |
---|
1421 | |
---|
1422 | The first variation of @Enum@ that is provided is also a subclass of @int@. |
---|
1423 | Members of an @IntEnum@ can be compared to integers; |
---|
1424 | by extension, integer enumerations of different types can also be compared to each other: |
---|
1425 | \begin{python} |
---|
1426 | >>> from enum import IntEnum |
---|
1427 | >>> class Shape(IntEnum): |
---|
1428 | ... CIRCLE = 1 |
---|
1429 | ... SQUARE = 2 |
---|
1430 | ... |
---|
1431 | >>> class Request(IntEnum): |
---|
1432 | ... POST = 1 |
---|
1433 | ... GET = 2 |
---|
1434 | ... |
---|
1435 | >>> Shape == 1 |
---|
1436 | False |
---|
1437 | >>> Shape.CIRCLE == 1 |
---|
1438 | True |
---|
1439 | >>> Shape.CIRCLE == Request.POST |
---|
1440 | True |
---|
1441 | \end{python} |
---|
1442 | However, they still can't be compared to standard @Enum@ enumerations: |
---|
1443 | \begin{python} |
---|
1444 | >>> class Shape(IntEnum): |
---|
1445 | ... CIRCLE = 1 |
---|
1446 | ... SQUARE = 2 |
---|
1447 | ... |
---|
1448 | >>> class Color(Enum): |
---|
1449 | ... RED = 1 |
---|
1450 | ... GREEN = 2 |
---|
1451 | ... |
---|
1452 | >>> Shape.CIRCLE == Color.RED |
---|
1453 | False |
---|
1454 | \end{python} |
---|
1455 | @IntEnum@ values behave like integers in other ways you'd expect: |
---|
1456 | \begin{python} |
---|
1457 | >>> int(Shape.CIRCLE) |
---|
1458 | 1 |
---|
1459 | >>> ['a', 'b', 'c'][Shape.CIRCLE] |
---|
1460 | 'b' |
---|
1461 | >>> [i for i in range(Shape.SQUARE)] |
---|
1462 | [0, 1] |
---|
1463 | \end{python} |
---|
1464 | |
---|
1465 | \subsection{StrEnum} |
---|
1466 | |
---|
1467 | The second variation of @Enum@ that is provided is also a subclass of @str@. |
---|
1468 | Members of a @StrEnum@ can be compared to strings; |
---|
1469 | by extension, string enumerations of different types can also be compared to each other. |
---|
1470 | |
---|
1471 | New in version 3.11. |
---|
1472 | |
---|
1473 | \subsection{IntFlag} |
---|
1474 | |
---|
1475 | The next variation of @Enum@ provided, @IntFlag@, is also based on @int@. |
---|
1476 | The difference being @IntFlag@ members can be combined using the bitwise operators (@&, |, ^, ~@) and the result is still an @IntFlag@ member, if possible. |
---|
1477 | Like @IntEnum@, @IntFlag@ members are also integers and can be used wherever an int is used. |
---|
1478 | |
---|
1479 | Note: Any operation on an IntFlag member besides the bit-wise operations will lose the @IntFlag@ membership. |
---|
1480 | |
---|
1481 | Bit-wise operations that result in invalid @IntFlag@ values will lose the @IntFlag@ membership. |
---|
1482 | See @FlagBoundary@ for details. |
---|
1483 | |
---|
1484 | New in version 3.6. |
---|
1485 | |
---|
1486 | Changed in version 3.11. |
---|
1487 | |
---|
1488 | Sample @IntFlag@ class: |
---|
1489 | \begin{python} |
---|
1490 | >>> from enum import IntFlag |
---|
1491 | >>> class Perm(IntFlag): |
---|
1492 | ... R = 4 |
---|
1493 | ... W = 2 |
---|
1494 | ... X = 1 |
---|
1495 | ... |
---|
1496 | >>> Perm.R | Perm.W |
---|
1497 | <Perm.R|W: 6> |
---|
1498 | >>> Perm.R + Perm.W |
---|
1499 | 6 |
---|
1500 | >>> RW = Perm.R | Perm.W |
---|
1501 | >>> Perm.R in RW |
---|
1502 | True |
---|
1503 | \end{python} |
---|
1504 | It is also possible to name the combinations: |
---|
1505 | \begin{python} |
---|
1506 | >>> class Perm(IntFlag): |
---|
1507 | ... R = 4 |
---|
1508 | ... W = 2 |
---|
1509 | ... X = 1 |
---|
1510 | ... RWX = 7 |
---|
1511 | ... |
---|
1512 | >>> Perm.RWX |
---|
1513 | <Perm.RWX: 7> |
---|
1514 | >>> ~Perm.RWX |
---|
1515 | <Perm: 0> |
---|
1516 | >>> Perm(7) |
---|
1517 | <Perm.RWX: 7> |
---|
1518 | \end{python} |
---|
1519 | Note: Named combinations are considered aliases. Aliases do not show up during iteration, but can be returned from by-value lookups. |
---|
1520 | |
---|
1521 | Changed in version 3.11. |
---|
1522 | |
---|
1523 | Another important difference between @IntFlag@ and @Enum@ is that if no flags are set (the value is 0), its boolean evaluation is @False@: |
---|
1524 | \begin{python} |
---|
1525 | >>> Perm.R & Perm.X |
---|
1526 | <Perm: 0> |
---|
1527 | >>> bool(Perm.R & Perm.X) |
---|
1528 | False |
---|
1529 | \end{python} |
---|
1530 | Because @IntFlag@ members are also subclasses of int they can be combined with them (but may lose @IntFlag@ membership: |
---|
1531 | \begin{python} |
---|
1532 | >>> Perm.X | 4 |
---|
1533 | <Perm.R|X: 5> |
---|
1534 | |
---|
1535 | >>> Perm.X + 8 |
---|
1536 | 9 |
---|
1537 | \end{python} |
---|
1538 | Note: The negation operator, @~@, always returns an @IntFlag@ member with a positive value: |
---|
1539 | \begin{python} |
---|
1540 | >>> (~Perm.X).value == (Perm.R|Perm.W).value == 6 |
---|
1541 | True |
---|
1542 | \end{python} |
---|
1543 | @IntFlag@ members can also be iterated over: |
---|
1544 | \begin{python} |
---|
1545 | >>> list(RW) |
---|
1546 | [<Perm.R: 4>, <Perm.W: 2>] |
---|
1547 | \end{python} |
---|
1548 | New in version 3.11. |
---|
1549 | |
---|
1550 | \subsection{Flag} |
---|
1551 | |
---|
1552 | The last variation is @Flag@. |
---|
1553 | Like @IntFlag@, @Flag@ members can be combined using the bitwise operators (@&, |, ^, ~@). |
---|
1554 | Unlike @IntFlag@, they cannot be combined with, nor compared against, any other @Flag@ enumeration, nor @int@. |
---|
1555 | While it is possible to specify the values directly it is recommended to use @auto@ as the value and let @Flag@ select an appropriate value. |
---|
1556 | |
---|
1557 | New in version 3.6. |
---|
1558 | |
---|
1559 | Like @IntFlag@, if a combination of @Flag@ members results in no flags being set, the boolean evaluation is @False@: |
---|
1560 | \begin{python} |
---|
1561 | >>> from enum import Flag, auto |
---|
1562 | >>> class Color(Flag): |
---|
1563 | ... RED = auto() |
---|
1564 | ... BLUE = auto() |
---|
1565 | ... GREEN = auto() |
---|
1566 | ... |
---|
1567 | >>> Color.RED & Color.GREEN |
---|
1568 | <Color: 0> |
---|
1569 | >>> bool(Color.RED & Color.GREEN) |
---|
1570 | False |
---|
1571 | \end{python} |
---|
1572 | Individual flags should have values that are powers of two (1, 2, 4, 8, ...), while combinations of flags will not: |
---|
1573 | \begin{python} |
---|
1574 | >>> class Color(Flag): |
---|
1575 | ... RED = auto() |
---|
1576 | ... BLUE = auto() |
---|
1577 | ... GREEN = auto() |
---|
1578 | ... WHITE = RED | BLUE | GREEN |
---|
1579 | ... |
---|
1580 | >>> Color.WHITE |
---|
1581 | <Color.WHITE: 7> |
---|
1582 | \end{python} |
---|
1583 | Giving a name to the ``no flags set'' condition does not change its boolean value: |
---|
1584 | \begin{python} |
---|
1585 | >>> class Color(Flag): |
---|
1586 | ... BLACK = 0 |
---|
1587 | ... RED = auto() |
---|
1588 | ... BLUE = auto() |
---|
1589 | ... GREEN = auto() |
---|
1590 | ... |
---|
1591 | >>> Color.BLACK |
---|
1592 | <Color.BLACK: 0> |
---|
1593 | >>> bool(Color.BLACK) |
---|
1594 | False |
---|
1595 | \end{python} |
---|
1596 | @Flag@ members can also be iterated over: |
---|
1597 | \begin{python} |
---|
1598 | >>> purple = Color.RED | Color.BLUE |
---|
1599 | >>> list(purple) |
---|
1600 | [<Color.RED: 1>, <Color.BLUE: 2>] |
---|
1601 | \end{python} |
---|
1602 | New in version 3.11. |
---|
1603 | |
---|
1604 | Note: For the majority of new code, @Enum@ and @Flag@ are strongly recommended, since @IntEnum@ and @IntFlag@ break some semantic promises of an enumeration (by being comparable to integers, and thus by transitivity to other unrelated enumerations). |
---|
1605 | @IntEnum@ and @IntFlag@ should be used only in cases where @Enum@ and @Flag@ will not do; |
---|
1606 | for example, when integer constants are replaced with enumerations, or for interoperability with other systems. |
---|
1607 | |
---|
1608 | \subsection{Others} |
---|
1609 | |
---|
1610 | While @IntEnum@ is part of the enum module, it would be very simple to implement independently: |
---|
1611 | \begin{python} |
---|
1612 | class IntEnum(int, Enum): |
---|
1613 | pass |
---|
1614 | \end{python} |
---|
1615 | This demonstrates how similar derived enumerations can be defined; |
---|
1616 | for example a @FloatEnum@ that mixes in float instead of @int@. |
---|
1617 | |
---|
1618 | Some rules: |
---|
1619 | \begin{itemize} |
---|
1620 | \item |
---|
1621 | When subclassing @Enum@, mix-in types must appear before @Enum@ itself in the sequence of bases, as in the @IntEnum@ example above. |
---|
1622 | \item |
---|
1623 | Mix-in types must be subclassable. |
---|
1624 | For example, @bool@ and @range@ are not subclassable and will throw an error during Enum creation if used as the mix-in type. |
---|
1625 | \item |
---|
1626 | While @Enum@ can have members of any type, once you mix in an additional type, all the members must have values of that type, e.g. @int@ above. |
---|
1627 | This restriction does not apply to mix-ins which only add methods and don't specify another type. |
---|
1628 | \item |
---|
1629 | When another data type is mixed in, the value attribute is not the same as the enum member itself, although it is equivalent and will compare equal. |
---|
1630 | \item |
---|
1631 | A data type is a mixin that defines @__new__()@, or a @dataclass@ |
---|
1632 | \item |
---|
1633 | \%-style formatting: @%s@ and @%r@ call the @Enum@ class's @__str__()@ and @__repr__()@ respectively; other codes (such as @%i@ or @%h@ for @IntEnum@) treat the enum member as its mixed-in type. |
---|
1634 | \item |
---|
1635 | Formatted string literals, @str.format()@, and format() will use the enum's @__str__()@ method. |
---|
1636 | \end{itemize} |
---|
1637 | Note: Because @IntEnum@, @IntFlag@, and @StrEnum@ are designed to be drop-in replacements for existing constants, their @__str__()@ method has been reset to their data types' @__str__()@ method. |
---|
1638 | |
---|
1639 | \subsection{When to use \lstinline{__new__()} vs. \lstinline{__init__()}} |
---|
1640 | |
---|
1641 | @__new__()@ must be used whenever you want to customize the actual value of the @Enum@ member. |
---|
1642 | Any other modifications may go in either @__new__()@ or @__init__()@, with @__init__()@ being preferred. |
---|
1643 | |
---|
1644 | For example, if you want to pass several items to the constructor, but only want one of them to be the value: |
---|
1645 | \begin{python} |
---|
1646 | >>> class Coordinate(bytes, Enum): |
---|
1647 | ... """ |
---|
1648 | ... Coordinate with binary codes that can be indexed by the int code. |
---|
1649 | ... """ |
---|
1650 | ... def __new__(cls, value, label, unit): |
---|
1651 | ... obj = bytes.__new__(cls, [value]) |
---|
1652 | ... obj._value_ = value |
---|
1653 | ... obj.label = label |
---|
1654 | ... obj.unit = unit |
---|
1655 | ... return obj |
---|
1656 | ... PX = (0, 'P.X', 'km') |
---|
1657 | ... PY = (1, 'P.Y', 'km') |
---|
1658 | ... VX = (2, 'V.X', 'km/s') |
---|
1659 | ... VY = (3, 'V.Y', 'km/s') |
---|
1660 | |
---|
1661 | >>> print(Coordinate['PY']) |
---|
1662 | Coordinate.PY |
---|
1663 | |
---|
1664 | >>> print(Coordinate(3)) |
---|
1665 | Coordinate.VY |
---|
1666 | \end{python} |
---|
1667 | Warning: Do not call @super().__new__()@, as the lookup-only @__new__@ is the one that is found; instead, use the data type directly. |
---|
1668 | |
---|
1669 | \subsection{Finer Points} |
---|
1670 | |
---|
1671 | Supported @__dunder__@ names |
---|
1672 | |
---|
1673 | @__members__@ is a read-only ordered mapping of member\_name:member items. It is only available on the class. |
---|
1674 | |
---|
1675 | @__new__()@, if specified, must create and return the enum members; it is also a very good idea to set the member's @_value_@ appropriately. Once all the members are created it is no longer used. |
---|
1676 | Supported @_sunder_@ names |
---|
1677 | \begin{itemize} |
---|
1678 | \item |
---|
1679 | @_name_@ -- name of the member |
---|
1680 | \item |
---|
1681 | @_value_@ -- value of the member; can be set / modified in @__new__@ |
---|
1682 | \item |
---|
1683 | @_missing_@ -- a lookup function used when a value is not found; may be overridden |
---|
1684 | \item |
---|
1685 | @_ignore_@ -- a list of names, either as a @list@ or a @str@, that will not be transformed into members, and will be removed from the final class |
---|
1686 | \item |
---|
1687 | @_order_@ -- used in Python 2/3 code to ensure member order is consistent (class attribute, removed during class creation) |
---|
1688 | \item |
---|
1689 | @_generate_@next@_value_@ -- used by the Functional API and by @auto@ to get an appropriate value for an enum member; may be overridden |
---|
1690 | \end{itemize} |
---|
1691 | Note: For standard @Enum@ classes the next value chosen is the last value seen incremented by one. |
---|
1692 | |
---|
1693 | For @Flag@ classes the next value chosen will be the next highest power-of-two, regardless of the last value seen. |
---|
1694 | |
---|
1695 | New in version 3.6: @_missing_@, @_order_@, @_generate_@next@_value_@ |
---|
1696 | |
---|
1697 | New in version 3.7: @_ignore_@ |
---|
1698 | |
---|
1699 | To help keep Python 2 / Python 3 code in sync an @_order_@ attribute can be provided. |
---|
1700 | It will be checked against the actual order of the enumeration and raise an error if the two do not match: |
---|
1701 | \begin{python} |
---|
1702 | >>> class Color(Enum): |
---|
1703 | ... _order_ = 'RED GREEN BLUE' |
---|
1704 | ... RED = 1 |
---|
1705 | ... BLUE = 3 |
---|
1706 | ... GREEN = 2 |
---|
1707 | ... |
---|
1708 | Traceback (most recent call last): |
---|
1709 | ... |
---|
1710 | TypeError: member order does not match _order_: |
---|
1711 | ['RED', 'BLUE', 'GREEN'] |
---|
1712 | ['RED', 'GREEN', 'BLUE'] |
---|
1713 | \end{python} |
---|
1714 | Note: In Python 2 code the @_order_@ attribute is necessary as definition order is lost before it can be recorded. |
---|
1715 | |
---|
1716 | \subsection{\lstinline{_Private__names}} |
---|
1717 | |
---|
1718 | Private names are not converted to enum members, but remain normal attributes. |
---|
1719 | |
---|
1720 | Changed in version 3.11. |
---|
1721 | |
---|
1722 | \subsection{\lstinline{Enum} member type} |
---|
1723 | |
---|
1724 | @Enum@ members are instances of their enum class, and are normally accessed as @EnumClass.member@. |
---|
1725 | In certain situations, such as writing custom enum behavior, being able to access one member directly from another is useful, and is supported; |
---|
1726 | however, in order to avoid name clashes between member names and attributes/methods from mixed-in classes, upper-case names are strongly recommended. |
---|
1727 | |
---|
1728 | Changed in version 3.5. |
---|
1729 | |
---|
1730 | \subsection{Creating members that are mixed with other data types} |
---|
1731 | |
---|
1732 | When subclassing other data types, such as @int@ or @str@, with an @Enum@, all values after the = @are@ passed to that data type's constructor. For example: |
---|
1733 | \begin{python} |
---|
1734 | >>> class MyEnum(IntEnum): # help(int) -> int(x, base=10) -> integer |
---|
1735 | ... example = '11', 16 # so x='11' and base=16 |
---|
1736 | ... |
---|
1737 | MyEnum.example.value # and hex(11) is... |
---|
1738 | 17 |
---|
1739 | \end{python} |
---|
1740 | |
---|
1741 | \subsection{\lstinline{Boolean} value of \lstinline{Enum} classes and members} |
---|
1742 | |
---|
1743 | Enum classes that are mixed with non-@Enum@ types (such as @int@, @str@, etc.) are evaluated according to the mixed-in type's rules; |
---|
1744 | otherwise, all members evaluate as @True@. |
---|
1745 | To make your own enum's boolean evaluation depend on the member's value add the following to your class: |
---|
1746 | \begin{python} |
---|
1747 | def __bool__(self): |
---|
1748 | return bool(self.value) |
---|
1749 | \end{python} |
---|
1750 | Plain @Enum@ classes always evaluate as @True@. |
---|
1751 | |
---|
1752 | \subsection{\lstinline{Enum} classes with methods} |
---|
1753 | |
---|
1754 | If you give your enum subclass extra methods, like the Planet class below, those methods will show up in a dir() of the member, but not of the class: |
---|
1755 | \begin{python} |
---|
1756 | >>> dir(Planet) |
---|
1757 | ['EARTH', 'JUPITER', 'MARS', 'MERCURY', 'NEPTUNE', 'SATURN', 'URANUS', 'VENUS', |
---|
1758 | '__class__', '__doc__', '__members__', '__module__'] |
---|
1759 | >>> dir(Planet.EARTH) |
---|
1760 | ['__class__', '__doc__', '__module__', 'mass', 'name', 'radius', 'surface_gravity', 'value'] |
---|
1761 | \end{python} |
---|
1762 | |
---|
1763 | \subsection{Combining members of \lstinline{Flag}} |
---|
1764 | |
---|
1765 | Iterating over a combination of @Flag@ members will only return the members that are comprised of a single bit: |
---|
1766 | \begin{python} |
---|
1767 | >>> class Color(Flag): |
---|
1768 | ... RED = auto() |
---|
1769 | ... GREEN = auto() |
---|
1770 | ... BLUE = auto() |
---|
1771 | ... MAGENTA = RED | BLUE |
---|
1772 | ... YELLOW = RED | GREEN |
---|
1773 | ... CYAN = GREEN | BLUE |
---|
1774 | ... |
---|
1775 | >>> Color(3) # named combination |
---|
1776 | <Color.YELLOW: 3> |
---|
1777 | >>> Color(7) # not named combination |
---|
1778 | <Color.RED|GREEN|BLUE: 7> |
---|
1779 | \end{python} |
---|
1780 | |
---|
1781 | \subsection{\lstinline{Flag} and \lstinline{IntFlag} minutia} |
---|
1782 | |
---|
1783 | Using the following snippet for our examples: |
---|
1784 | \begin{python} |
---|
1785 | >>> class Color(IntFlag): |
---|
1786 | ... BLACK = 0 |
---|
1787 | ... RED = 1 |
---|
1788 | ... GREEN = 2 |
---|
1789 | ... BLUE = 4 |
---|
1790 | ... PURPLE = RED | BLUE |
---|
1791 | ... WHITE = RED | GREEN | BLUE |
---|
1792 | ... |
---|
1793 | \end{python} |
---|
1794 | the following are true: |
---|
1795 | \begin{itemize} |
---|
1796 | \item |
---|
1797 | single-bit flags are canonical |
---|
1798 | \item |
---|
1799 | multi-bit and zero-bit flags are aliases |
---|
1800 | \item |
---|
1801 | only canonical flags are returned during iteration: |
---|
1802 | \begin{python} |
---|
1803 | >>> list(Color.WHITE) |
---|
1804 | [<Color.RED: 1>, <Color.GREEN: 2>, <Color.BLUE: 4>] |
---|
1805 | \end{python} |
---|
1806 | negating a flag or flag set returns a new flag/flag set with the corresponding positive integer value: |
---|
1807 | \begin{python} |
---|
1808 | >>> Color.BLUE |
---|
1809 | <Color.BLUE: 4> |
---|
1810 | |
---|
1811 | >>> ~Color.BLUE |
---|
1812 | <Color.RED|GREEN: 3> |
---|
1813 | \end{python} |
---|
1814 | \item |
---|
1815 | names of pseudo-flags are constructed from their members' names: |
---|
1816 | \begin{python} |
---|
1817 | >>> (Color.RED | Color.GREEN).name |
---|
1818 | 'RED|GREEN' |
---|
1819 | \end{python} |
---|
1820 | \item |
---|
1821 | multi-bit flags, aka aliases, can be returned from operations: |
---|
1822 | \begin{python} |
---|
1823 | >>> Color.RED | Color.BLUE |
---|
1824 | <Color.PURPLE: 5> |
---|
1825 | |
---|
1826 | >>> Color(7) # or Color(-1) |
---|
1827 | <Color.WHITE: 7> |
---|
1828 | |
---|
1829 | >>> Color(0) |
---|
1830 | <Color.BLACK: 0> |
---|
1831 | \end{python} |
---|
1832 | \item |
---|
1833 | membership / containment checking: zero-valued flags are always considered to be contained: |
---|
1834 | \begin{python} |
---|
1835 | >>> Color.BLACK in Color.WHITE |
---|
1836 | True |
---|
1837 | \end{python} |
---|
1838 | otherwise, only if all bits of one flag are in the other flag will True be returned: |
---|
1839 | \begin{python} |
---|
1840 | >>> Color.PURPLE in Color.WHITE |
---|
1841 | True |
---|
1842 | |
---|
1843 | >>> Color.GREEN in Color.PURPLE |
---|
1844 | False |
---|
1845 | \end{python} |
---|
1846 | \end{itemize} |
---|
1847 | There is a new boundary mechanism that controls how out-of-range / invalid bits are handled: @STRICT@, @CONFORM@, @EJECT@, and @KEEP@: |
---|
1848 | \begin{itemize} |
---|
1849 | \item |
---|
1850 | @STRICT@ --> raises an exception when presented with invalid values |
---|
1851 | \item |
---|
1852 | @CONFORM@ --> discards any invalid bits |
---|
1853 | \item |
---|
1854 | @EJECT@ --> lose Flag status and become a normal int with the given value |
---|
1855 | \item |
---|
1856 | @KEEP@ --> keep the extra bits |
---|
1857 | \begin{itemize} |
---|
1858 | \item |
---|
1859 | keeps Flag status and extra bits |
---|
1860 | \item |
---|
1861 | extra bits do not show up in iteration |
---|
1862 | \item |
---|
1863 | extra bits do show up in repr() and str() |
---|
1864 | \end{itemize} |
---|
1865 | \end{itemize} |
---|
1866 | The default for @Flag@ is @STRICT@, the default for @IntFlag@ is @EJECT@, and the default for @_convert_@ is @KEEP@ (see @ssl.Options@ for an example of when @KEEP@ is needed). |
---|
1867 | |
---|
1868 | \section{How are Enums and Flags different?} |
---|
1869 | |
---|
1870 | Enums have a custom metaclass that affects many aspects of both derived @Enum@ classes and their instances (members). |
---|
1871 | |
---|
1872 | \subsection{Enum Classes} |
---|
1873 | |
---|
1874 | The @EnumType@ metaclass is responsible for providing the @__contains__()@, @__dir__()@, @__iter__()@ and other methods that allow one to do things with an @Enum@ class that fail on a typical class, such as @list(Color)@ or @some_enum_var@ in @Color@. |
---|
1875 | @EnumType@ is responsible for ensuring that various other methods on the final @Enum@ class are correct (such as @__new__()@, @__getnewargs__()@, @__str__()@ and @__repr__()@). |
---|
1876 | |
---|
1877 | \subsection{Flag Classes} |
---|
1878 | |
---|
1879 | Flags have an expanded view of aliasing: to be canonical, the value of a flag needs to be a power-of-two value, and not a duplicate name. |
---|
1880 | So, in addition to the @Enum@ definition of alias, a flag with no value (a.k.a. 0) or with more than one power-of-two value (e.g. 3) is considered an alias. |
---|
1881 | |
---|
1882 | \subsection{Enum Members (aka instances)} |
---|
1883 | |
---|
1884 | The most interesting thing about enum members is that they are singletons. |
---|
1885 | @EnumType@ creates them all while it is creating the enum class itself, and then puts a custom @__new__()@ in place to ensure that no new ones are ever instantiated by returning only the existing member instances. |
---|
1886 | |
---|
1887 | \subsection{Flag Members} |
---|
1888 | |
---|
1889 | Flag members can be iterated over just like the @Flag@ class, and only the canonical members will be returned. |
---|
1890 | For example: |
---|
1891 | \begin{python} |
---|
1892 | >>> list(Color) |
---|
1893 | [<Color.RED: 1>, <Color.GREEN: 2>, <Color.BLUE: 4>] |
---|
1894 | \end{python} |
---|
1895 | (Note that BLACK, PURPLE, and WHITE do not show up.) |
---|
1896 | |
---|
1897 | Inverting a flag member returns the corresponding positive value, rather than a negative value -- for example: |
---|
1898 | \begin{python} |
---|
1899 | >>> ~Color.RED |
---|
1900 | <Color.GREEN|BLUE: 6> |
---|
1901 | \end{python} |
---|
1902 | Flag members have a length corresponding to the number of power-of-two values they contain. For example: |
---|
1903 | \begin{python} |
---|
1904 | >>> len(Color.PURPLE) |
---|
1905 | 2 |
---|
1906 | \end{python} |
---|
1907 | |
---|
1908 | \subsection{Enum Cookbook} |
---|
1909 | |
---|
1910 | While @Enum@, @IntEnum@, @StrEnum@, @Flag@, and @IntFlag@ are expected to cover the majority of use-cases, they cannot cover them all. Here are recipes for some different types of enumerations that can be used directly, or as examples for creating one's own. |
---|
1911 | |
---|
1912 | \subsection{Omitting values} |
---|
1913 | |
---|
1914 | In many use-cases, one doesn't care what the actual value of an enumeration is. There are several ways to define this type of simple enumeration: |
---|
1915 | \begin{itemize} |
---|
1916 | \item |
---|
1917 | use instances of auto for the value |
---|
1918 | \item |
---|
1919 | use instances of object as the value |
---|
1920 | \item |
---|
1921 | use a descriptive string as the value |
---|
1922 | \item |
---|
1923 | use a tuple as the value and a custom @__new__()@ to replace the tuple with an @int@ value |
---|
1924 | \end{itemize} |
---|
1925 | Using any of these methods signifies to the user that these values are not important, and also enables one to add, remove, or reorder members without having to renumber the remaining members. |
---|
1926 | |
---|
1927 | \subsection{Using \lstinline{auto}} |
---|
1928 | |
---|
1929 | Using @auto@ would look like: |
---|
1930 | \begin{python} |
---|
1931 | >>> class Color(Enum): |
---|
1932 | ... RED = auto() |
---|
1933 | ... BLUE = auto() |
---|
1934 | ... GREEN = auto() |
---|
1935 | ... |
---|
1936 | >>> Color.GREEN |
---|
1937 | <Color.GREEN: 3> |
---|
1938 | \end{python} |
---|
1939 | |
---|
1940 | \subsection{Using \lstinline{object}} |
---|
1941 | |
---|
1942 | Using @object@ would look like: |
---|
1943 | \begin{python} |
---|
1944 | >>> class Color(Enum): |
---|
1945 | ... RED = object() |
---|
1946 | ... GREEN = object() |
---|
1947 | ... BLUE = object() |
---|
1948 | ... |
---|
1949 | >>> Color.GREEN |
---|
1950 | <Color.GREEN: <object object at 0x...>> |
---|
1951 | \end{python} |
---|
1952 | This is also a good example of why you might want to write your own @__repr__()@: |
---|
1953 | \begin{python} |
---|
1954 | >>> class Color(Enum): |
---|
1955 | ... RED = object() |
---|
1956 | ... GREEN = object() |
---|
1957 | ... BLUE = object() |
---|
1958 | ... def __repr__(self): |
---|
1959 | ... return "<%s.%s>" % (self.__class__.__name__, self._name_) |
---|
1960 | ... |
---|
1961 | >>> Color.GREEN |
---|
1962 | <Color.GREEN> |
---|
1963 | \end{python} |
---|
1964 | |
---|
1965 | \subsection{Using a descriptive string} |
---|
1966 | |
---|
1967 | Using a string as the value would look like: |
---|
1968 | \begin{python} |
---|
1969 | >>> class Color(Enum): |
---|
1970 | ... RED = 'stop' |
---|
1971 | ... GREEN = 'go' |
---|
1972 | ... BLUE = 'too fast!' |
---|
1973 | ... |
---|
1974 | >>> Color.GREEN |
---|
1975 | <Color.GREEN: 'go'> |
---|
1976 | \end{python} |
---|
1977 | |
---|
1978 | \subsection{Using a custom \lstinline{__new__()}} |
---|
1979 | |
---|
1980 | Using an auto-numbering @__new__()@ would look like: |
---|
1981 | \begin{python} |
---|
1982 | >>> class AutoNumber(Enum): |
---|
1983 | ... def __new__(cls): |
---|
1984 | ... value = len(cls.__members__) + 1 |
---|
1985 | ... obj = object.__new__(cls) |
---|
1986 | ... obj._value_ = value |
---|
1987 | ... return obj |
---|
1988 | ... |
---|
1989 | >>> class Color(AutoNumber): |
---|
1990 | ... RED = () |
---|
1991 | ... GREEN = () |
---|
1992 | ... BLUE = () |
---|
1993 | ... |
---|
1994 | >>> Color.GREEN |
---|
1995 | <Color.GREEN: 2> |
---|
1996 | \end{python} |
---|
1997 | To make a more general purpose @AutoNumber@, add @*args@ to the signature: |
---|
1998 | \begin{python} |
---|
1999 | >>> class AutoNumber(Enum): |
---|
2000 | ... def __new__(cls, *args): # this is the only change from above |
---|
2001 | ... value = len(cls.__members__) + 1 |
---|
2002 | ... obj = object.__new__(cls) |
---|
2003 | ... obj._value_ = value |
---|
2004 | ... return obj |
---|
2005 | \end{python} |
---|
2006 | Then when you inherit from @AutoNumber@ you can write your own @__init__@ to handle any extra arguments: |
---|
2007 | \begin{python} |
---|
2008 | >>> class Swatch(AutoNumber): |
---|
2009 | ... def __init__(self, pantone='unknown'): |
---|
2010 | ... self.pantone = pantone |
---|
2011 | ... AUBURN = '3497' |
---|
2012 | ... SEA_GREEN = '1246' |
---|
2013 | ... BLEACHED_CORAL = () # New color, no Pantone code yet! |
---|
2014 | ... |
---|
2015 | >>> Swatch.SEA_GREEN |
---|
2016 | <Swatch.SEA_GREEN: 2> |
---|
2017 | >>> Swatch.SEA_GREEN.pantone |
---|
2018 | '1246' |
---|
2019 | >>> Swatch.BLEACHED_CORAL.pantone |
---|
2020 | 'unknown' |
---|
2021 | \end{python} |
---|
2022 | Note: The @__new__()@ method, if defined, is used during creation of the Enum members; |
---|
2023 | it is then replaced by Enum's @__new__()@ which is used after class creation for lookup of existing members. |
---|
2024 | |
---|
2025 | Warning: Do not call @super().__new__()@, as the lookup-only @__new__@ is the one that is found; |
---|
2026 | instead, use the data type directly -- e.g.: |
---|
2027 | \begin{python} |
---|
2028 | obj = int.__new__(cls, value) |
---|
2029 | \end{python} |
---|
2030 | |
---|
2031 | \subsection{OrderedEnum} |
---|
2032 | |
---|
2033 | An ordered enumeration that is not based on @IntEnum@ and so maintains the normal @Enum@ invariants (such as not being comparable to other enumerations): |
---|
2034 | \begin{python} |
---|
2035 | >>> class OrderedEnum(Enum): |
---|
2036 | ... def __ge__(self, other): |
---|
2037 | ... if self.__class__ is other.__class__: |
---|
2038 | ... return self.value >= other.value |
---|
2039 | ... return NotImplemented |
---|
2040 | ... def __gt__(self, other): |
---|
2041 | ... if self.__class__ is other.__class__: |
---|
2042 | ... return self.value > other.value |
---|
2043 | ... return NotImplemented |
---|
2044 | ... def __le__(self, other): |
---|
2045 | ... if self.__class__ is other.__class__: |
---|
2046 | ... return self.value <= other.value |
---|
2047 | ... return NotImplemented |
---|
2048 | ... def __lt__(self, other): |
---|
2049 | ... if self.__class__ is other.__class__: |
---|
2050 | ... return self.value < other.value |
---|
2051 | ... return NotImplemented |
---|
2052 | ... |
---|
2053 | >>> class Grade(OrderedEnum): |
---|
2054 | ... A = 5 |
---|
2055 | ... B = 4 |
---|
2056 | ... C = 3 |
---|
2057 | ... D = 2 |
---|
2058 | ... F = 1 |
---|
2059 | >>> Grade.C < Grade.A |
---|
2060 | True |
---|
2061 | \end{python} |
---|
2062 | |
---|
2063 | \subsection{DuplicateFreeEnum} |
---|
2064 | |
---|
2065 | Raises an error if a duplicate member value is found instead of creating an alias: |
---|
2066 | \begin{python} |
---|
2067 | >>> class DuplicateFreeEnum(Enum): |
---|
2068 | ... def __init__(self, *args): |
---|
2069 | ... cls = self.__class__ |
---|
2070 | ... if any(self.value == e.value for e in cls): |
---|
2071 | ... a = self.name |
---|
2072 | ... e = cls(self.value).name |
---|
2073 | ... raise ValueError( |
---|
2074 | ... "aliases not allowed in DuplicateFreeEnum: %r --> %r" |
---|
2075 | ... % (a, e)) |
---|
2076 | >>> class Color(DuplicateFreeEnum): |
---|
2077 | ... RED = 1 |
---|
2078 | ... GREEN = 2 |
---|
2079 | ... BLUE = 3 |
---|
2080 | ... GRENE = 2 |
---|
2081 | ... |
---|
2082 | Traceback (most recent call last): |
---|
2083 | ... |
---|
2084 | ValueError: aliases not allowed in DuplicateFreeEnum: 'GRENE' --> 'GREEN' |
---|
2085 | \end{python} |
---|
2086 | Note: This is a useful example for subclassing Enum to add or change other behaviors as well as disallowing aliases. |
---|
2087 | If the only desired change is disallowing aliases, the @unique()@ decorator can be used instead. |
---|
2088 | |
---|
2089 | \subsection{Planet} |
---|
2090 | |
---|
2091 | If @__new__()@ or @__init__()@ is defined, the value of the enum member will be passed to those methods: |
---|
2092 | \begin{figure} |
---|
2093 | \begin{python} |
---|
2094 | from enum import Enum |
---|
2095 | class Planet(Enum): |
---|
2096 | MERCURY = ( 3.303E23, 2.4397E6 ) |
---|
2097 | VENUS = ( 4.869E24, 6.0518E6 ) |
---|
2098 | EARTH = (5.976E24, 6.37814E6) |
---|
2099 | MARS = (6.421E23, 3.3972E6) |
---|
2100 | JUPITER = (1.9E27, 7.1492E7) |
---|
2101 | SATURN = (5.688E26, 6.0268E7) |
---|
2102 | URANUS = (8.686E25, 2.5559E7) |
---|
2103 | NEPTUNE = (1.024E26, 2.4746E7) |
---|
2104 | def __init__( self, mass, radius ): |
---|
2105 | self.mass = mass # in kilograms |
---|
2106 | self.radius = radius # in meters |
---|
2107 | def surface_gravity( self ): |
---|
2108 | # universal gravitational constant (m3 kg-1 s-2) |
---|
2109 | G = 6.67300E-11 |
---|
2110 | return G * self.mass / (self.radius * self.radius) |
---|
2111 | for p in Planet: |
---|
2112 | print( f"{p.name}: {p.value}" ) |
---|
2113 | |
---|
2114 | MERCURY: (3.303e+23, 2439700.0) |
---|
2115 | VENUS: (4.869e+24, 6051800.0) |
---|
2116 | EARTH: (5.976e+24, 6378140.0) |
---|
2117 | MARS: (6.421e+23, 3397200.0) |
---|
2118 | JUPITER: (1.9e+27, 71492000.0) |
---|
2119 | SATURN: (5.688e+26, 60268000.0) |
---|
2120 | URANUS: (8.686e+25, 25559000.0) |
---|
2121 | NEPTUNE: (1.024e+26, 24746000.0) |
---|
2122 | \end{python} |
---|
2123 | \caption{Python Planet Example} |
---|
2124 | \label{f:PythonPlanetExample} |
---|
2125 | \end{figure} |
---|
2126 | |
---|
2127 | |
---|
2128 | \subsection{TimePeriod} |
---|
2129 | |
---|
2130 | An example to show the @_ignore_@ attribute in use: |
---|
2131 | \begin{python} |
---|
2132 | >>> from datetime import timedelta |
---|
2133 | >>> class Period(timedelta, Enum): |
---|
2134 | ... "different lengths of time" |
---|
2135 | ... _ignore_ = 'Period i' |
---|
2136 | ... Period = vars() |
---|
2137 | ... for i in range(367): |
---|
2138 | ... Period['day_%d' % i] = i |
---|
2139 | ... |
---|
2140 | >>> list(Period)[:2] |
---|
2141 | [<Period.day_0: datetime.timedelta(0)>, <Period.day_1: datetime.timedelta(days=1)>] |
---|
2142 | >>> list(Period)[-2:] |
---|
2143 | [<Period.day_365: datetime.timedelta(days=365)>, <Period.day_366: datetime.timedelta(days=366)>] |
---|
2144 | \end{python} |
---|
2145 | |
---|
2146 | \subsection{Subclassing EnumType} |
---|
2147 | |
---|
2148 | While most enum needs can be met by customizing @Enum@ subclasses, either with class decorators or custom functions, @EnumType@ can be subclassed to provide a different Enum experience. |
---|
2149 | |
---|
2150 | |
---|
2151 | \section{OCaml} |
---|
2152 | |
---|
2153 | % https://ocaml.org/docs/basic-data-types#enumerated-data-types |
---|
2154 | % https://dev.realworldocaml.org/runtime-memory-layout.html |
---|
2155 | |
---|
2156 | OCaml provides a variant (union) type, where multiple heterogeneously-typed objects share the same storage. |
---|
2157 | The simplest form of the variant type is a list of nullary datatype constructors, which is like an unscoped, opaque enumeration. |
---|
2158 | |
---|
2159 | OCaml provides a variant (union) type, which is an aggregation of heterogeneous types. |
---|
2160 | A basic variant is a list of nullary datatype constructors, which is like an unscoped, opaque enumeration. |
---|
2161 | \begin{ocaml} |
---|
2162 | type weekday = Mon | Tue | Wed | Thu | Fri | Sat | Sun |
---|
2163 | let day : weekday @= Mon@ $\C{(* bind *)}$ |
---|
2164 | let take_class( d : weekday ) = |
---|
2165 | @match@ d with $\C{(* matching *)}$ |
---|
2166 | Mon | Wed -> Printf.printf "CS442\n" | |
---|
2167 | Tue | Thu -> Printf.printf "CS343\n" | |
---|
2168 | Fri -> Printf.printf "Tutorial\n" | |
---|
2169 | _ -> Printf.printf "Take a break\n" |
---|
2170 | let _ = take_class( Mon ); |
---|
2171 | @CS442@ |
---|
2172 | \end{ocaml} |
---|
2173 | The only operations are binding and pattern matching (equality), where the variant name is logically the implementation tag stored in the union for discriminating the value in the object storage. |
---|
2174 | After compilation, variant names are mapped to an opague ascending intergral type discriminants, starting from 0. |
---|
2175 | Here, function @take_class@ has a @weekday@ parameter, and returns @"CS442"@, if the weekday value is @Mon@ or @Wed@, @"CS343"@, if the value is @Tue@ or @Thu@, and @"Tutorial"@ for @Fri@. |
---|
2176 | The ``@_@'' is a wildcard matching any @weekday@ value, so the function returns @"Take a break"@ for values @Sat@ or @Sun@, which are not matched by the previous cases. |
---|
2177 | Since the variant has no type, it has a \Newterm{0-arity constructor}, \ie no parameters. |
---|
2178 | Because @weekday@ is a union of values @Mon@ to @Sun@, it is a \Newterm{union type} in turns of the functional-programming paradigm. |
---|
2179 | |
---|
2180 | Each variant can have an associated heterogeneous type, with an n-ary constructor for creating a corresponding value. |
---|
2181 | \begin{ocaml} |
---|
2182 | type colour = Red | Green of @string@ | Blue of @int * float@ |
---|
2183 | \end{ocaml} |
---|
2184 | A variant with parameter is stored in a memory block, prefixed by an int tag and has its parameters stores as words in the block. |
---|
2185 | @colour@ is a summation of a nullary type, a unary product type of @string@, and a cross product of @int@ and @float@. |
---|
2186 | (Mathematically, a @Blue@ value is a Cartesian product of the types @int@ type and @float@.) |
---|
2187 | Hence, a variant type creates a sum of product of different types. |
---|
2188 | \begin{ocaml} |
---|
2189 | let c = Red $\C{(* 0-ary constructor, set tag *)}$ |
---|
2190 | let _ = match c with Red -> Printf.printf "Red, " |
---|
2191 | let c = Green( "abc" ) $\C{(* 1-ary constructor, set tag *)}$ |
---|
2192 | let _ = match c with Green g -> Printf.printf "%s, " g |
---|
2193 | let c = Blue( 1, 1.5 ) $\C{(* 2-ary constructor, set tag *)}$ |
---|
2194 | let _ = match c with Blue( i, f ) -> Printf.printf "%d %g\n" i f |
---|
2195 | @Red, abc, 1 1.5@ |
---|
2196 | \end{ocaml} |
---|
2197 | |
---|
2198 | A variant type can have a recursive definition. |
---|
2199 | \begin{ocaml} |
---|
2200 | type @stringList@ = Empty | Pair of string * @stringList@ |
---|
2201 | \end{ocaml} |
---|
2202 | which is a recursive sum of product of types, called an \Newterm{algebraic data-type}. |
---|
2203 | A recursive function is often used to pattern match against a recursive variant type. |
---|
2204 | \begin{ocaml} |
---|
2205 | let rec @len_of_string_list@( list : stringList ): int = |
---|
2206 | match list with |
---|
2207 | Empty -> 0 | |
---|
2208 | Pair( _ , r ) -> 1 + @len_of_string_list@ r |
---|
2209 | \end{ocaml} |
---|
2210 | Here, the head of the recursive type is removed and the remainder is processed until the type is empty. |
---|
2211 | Each recursion is counted to obtain the number of elements in the type. |
---|
2212 | |
---|
2213 | Note, the compiler statically guarantees that only the correct kind of type is used in the \lstinline[language=OCaml]{match} statement. |
---|
2214 | However, the union tag is dynamically set on binding (and possible reset on assignment), so a \lstinline[language=OCaml]{match} statement is effectively doing RTTI to select the matching case clause. |
---|
2215 | |
---|
2216 | In summary, an OCaml variant is a singleton value rather than a set of possibly ordered values, and hence, has no notion of enumerabilty. |
---|
2217 | Therefore it is not an enumeration, except for the simple opaque (nullary) case. |
---|
2218 | |
---|
2219 | \begin{comment} |
---|
2220 | Date: Wed, 13 Mar 2024 10:52:34 -0400 |
---|
2221 | Subject: Re: OCaml |
---|
2222 | To: "Peter A. Buhr" <pabuhr@uwaterloo.ca> |
---|
2223 | From: Gregor Richards <gregor.richards@uwaterloo.ca> |
---|
2224 | |
---|
2225 | On 3/12/24 18:34, Peter A. Buhr wrote: |
---|
2226 | > Gregor, attached is a section Jiada wrote on OCaml (1-page). |
---|
2227 | > Does it reflect our discussion about functional languages and enumerations? |
---|
2228 | |
---|
2229 | Yeah, I think so. The most important part, i.e., that once they're |
---|
2230 | parameterized they're not really enumerations at all, is covered clearly |
---|
2231 | enough. |
---|
2232 | |
---|
2233 | A couple quibbles: |
---|
2234 | |
---|
2235 | <<a list of untyped tags>> |
---|
2236 | |
---|
2237 | This is true, but leaking implementation details. These are nullary datatype |
---|
2238 | constructors. Indeed, you later talk about "tagged variants", which are really |
---|
2239 | just parameterized variants, using the term "tag" differently, confusing the |
---|
2240 | term "tag" further. |
---|
2241 | |
---|
2242 | <<Because weekday is a summation of values Mon to Sun, it is a sum type in |
---|
2243 | turns of the functional-programming paradigm>> |
---|
2244 | |
---|
2245 | It is a *union* of values and is a *union* type. |
---|
2246 | |
---|
2247 | With valediction, |
---|
2248 | - Gregor Richards |
---|
2249 | |
---|
2250 | |
---|
2251 | Date: Thu, 14 Mar 2024 21:45:52 -0400 |
---|
2252 | Subject: Re: OCaml "enums" do come with ordering |
---|
2253 | To: "Peter A. Buhr" <pabuhr@uwaterloo.ca> |
---|
2254 | From: Gregor Richards <gregor.richards@uwaterloo.ca> |
---|
2255 | |
---|
2256 | On 3/14/24 21:30, Peter A. Buhr wrote: |
---|
2257 | > I've marked 3 places with your name to shows places with enum ordering. |
---|
2258 | > |
---|
2259 | > type weekday = Mon | Tue | Wed | Thu | Fri | Sat | Sun |
---|
2260 | > let day : weekday = Mon |
---|
2261 | > let take_class( d : weekday ) = |
---|
2262 | > if d <= Fri then (* Gregor *) |
---|
2263 | > Printf.printf "weekday\n" |
---|
2264 | > else if d >= Sat then (* Gregor *) |
---|
2265 | > Printf.printf "weekend\n"; |
---|
2266 | > match d with |
---|
2267 | > Mon | Wed -> Printf.printf "CS442\n" | |
---|
2268 | > Tue | Thu -> Printf.printf "CS343\n" | |
---|
2269 | > Fri -> Printf.printf "Tutorial\n" | |
---|
2270 | > _ -> Printf.printf "Take a break\n" |
---|
2271 | > |
---|
2272 | > let _ = take_class( Mon ); take_class( Sat ); |
---|
2273 | > |
---|
2274 | > type colour = Red | Green of string | Blue of int * float |
---|
2275 | > let c = Red |
---|
2276 | > let _ = match c with Red -> Printf.printf "Red, " |
---|
2277 | > let c = Green( "abc" ) |
---|
2278 | > let _ = match c with Green g -> Printf.printf "%s, " g |
---|
2279 | > let c = Blue( 1, 1.5 ) |
---|
2280 | > let _ = match c with Blue( i, f ) -> Printf.printf "%d %g\n" i f |
---|
2281 | > |
---|
2282 | > let check_colour(c: colour): string = |
---|
2283 | > if c < Green( "xyz" ) then (* Gregor *) |
---|
2284 | > Printf.printf "green\n"; |
---|
2285 | > match c with |
---|
2286 | > Red -> "Red" | |
---|
2287 | > Green g -> g | |
---|
2288 | > Blue(i, f) -> string_of_int i ^ string_of_float f |
---|
2289 | > let _ = check_colour( Red ); check_colour( Green( "xyz" ) ); |
---|
2290 | > |
---|
2291 | > type stringList = Empty | Pair of string * stringList |
---|
2292 | > let rec len_of_string_list(l: stringList): int = |
---|
2293 | > match l with |
---|
2294 | > Empty -> 0 | |
---|
2295 | > Pair(_ , r) -> 1 + len_of_string_list r |
---|
2296 | > |
---|
2297 | > let _ = for i = 1 to 10 do |
---|
2298 | > Printf.printf "%d, " i |
---|
2299 | > done |
---|
2300 | > |
---|
2301 | > (* Local Variables: *) |
---|
2302 | > (* tab-width: 4 *) |
---|
2303 | > (* compile-command: "ocaml test.ml" *) |
---|
2304 | > (* End: *) |
---|
2305 | |
---|
2306 | My functional-language familiarity is far more with Haskell than OCaml. I |
---|
2307 | mostly view OCaml through a lens of "it's Haskell but with cheating". Haskell |
---|
2308 | "enums" (ADTs) aren't ordered unless you specifically and manually put them in |
---|
2309 | the Ord typeclass by defining the comparators. Apparently, OCaml has some |
---|
2310 | other rule, which I would guess is something like "sort by tag then by order of |
---|
2311 | parameter". Having a default behavior for comparators is *bizarre*; my guess |
---|
2312 | would be that it gained this behavior in its flirtation with object |
---|
2313 | orientation, but that's just a guess (and irrelevant). |
---|
2314 | |
---|
2315 | This gives a total order, but not enumerability (which would still be |
---|
2316 | effectively impossible or even meaningless since enums are just a special case |
---|
2317 | of ADTs). |
---|
2318 | |
---|
2319 | With valediction, |
---|
2320 | - Gregor Richards |
---|
2321 | |
---|
2322 | Date: Wed, 20 Mar 2024 18:16:44 -0400 |
---|
2323 | Subject: Re: |
---|
2324 | To: "Peter A. Buhr" <pabuhr@uwaterloo.ca> |
---|
2325 | From: Gregor Richards <gregor.richards@uwaterloo.ca> |
---|
2326 | |
---|
2327 | |
---|
2328 | On 3/20/24 17:26, Peter A. Buhr wrote: |
---|
2329 | > Gregor, everyone at this end would like a definition of "enumerability". Can |
---|
2330 | > you formulate one? |
---|
2331 | |
---|
2332 | According to the OED (emphasis added to the meaning I'm after): |
---|
2333 | |
---|
2334 | enumerate (verb, transitive). To count, ascertain the number of; **more |
---|
2335 | usually, to mention (a number of things or persons) separately, as if for the |
---|
2336 | purpose of counting**; to specify as in a list or catalogue. |
---|
2337 | |
---|
2338 | With C enums, if you know the lowest and highest value, you can simply loop |
---|
2339 | over them in a for loop (this is, of course, why so many enums come with an |
---|
2340 | ENUM_WHATEVER_LAST value). But, I would be hesitant to use the word "loop" to |
---|
2341 | describe enumerability, since in functional languages, you would recurse for |
---|
2342 | such a purpose. |
---|
2343 | |
---|
2344 | In Haskell, in order to do something with every member of an "enumeration", you |
---|
2345 | would have to explicitly list them all. The type system will help a bit since |
---|
2346 | it knows if you haven't listed them all, but you would have to statically have |
---|
2347 | every element in the enumeration. If somebody added new elements to the |
---|
2348 | enumeration later, your code to enumerate over them would no longer work |
---|
2349 | correctly, because you can't simply say "for each member of this enumeration do |
---|
2350 | X". In Haskell that's because there aren't actually enumerations; what they use |
---|
2351 | as enumerations are a degenerate form of algebraic datatypes, and ADTs are |
---|
2352 | certainly not enumerable. In OCaml, you've demonstrated that they impose |
---|
2353 | comparability, but I would still assume that you can't make a loop over every |
---|
2354 | member of an enumeration. (But, who knows!) |
---|
2355 | |
---|
2356 | Since that's literally what "enumerate" means, it seems like a rather important |
---|
2357 | property for enumerations to have ;) |
---|
2358 | |
---|
2359 | With valediction, |
---|
2360 | - Gregor Richards |
---|
2361 | |
---|
2362 | |
---|
2363 | From: Andrew James Beach <ajbeach@uwaterloo.ca> |
---|
2364 | To: Gregor Richards <gregor.richards@uwaterloo.ca>, Peter Buhr <pabuhr@uwaterloo.ca> |
---|
2365 | CC: Michael Leslie Brooks <mlbrooks@uwaterloo.ca>, Fangren Yu <f37yu@uwaterloo.ca>, |
---|
2366 | Jiada Liang <j82liang@uwaterloo.ca> |
---|
2367 | Subject: Re: Re: |
---|
2368 | Date: Thu, 21 Mar 2024 14:26:36 +0000 |
---|
2369 | |
---|
2370 | Does this mean that not all enum declarations in C create enumerations? If you |
---|
2371 | declare an enumeration like: |
---|
2372 | |
---|
2373 | enum Example { |
---|
2374 | Label, |
---|
2375 | Name = 10, |
---|
2376 | Tag = 3, |
---|
2377 | }; |
---|
2378 | |
---|
2379 | I don't think there is any way to enumerate (iterate, loop, recurse) over these |
---|
2380 | values without listing all of them. |
---|
2381 | |
---|
2382 | |
---|
2383 | Date: Thu, 21 Mar 2024 10:31:49 -0400 |
---|
2384 | Subject: Re: |
---|
2385 | To: Andrew James Beach <ajbeach@uwaterloo.ca>, Peter Buhr <pabuhr@uwaterloo.ca> |
---|
2386 | CC: Michael Leslie Brooks <mlbrooks@uwaterloo.ca>, Fangren Yu <f37yu@uwaterloo.ca>, |
---|
2387 | Jiada Liang <j82liang@uwaterloo.ca> |
---|
2388 | From: Gregor Richards <gregor.richards@uwaterloo.ca> |
---|
2389 | |
---|
2390 | I consider this conclusion reasonable. C enums can be nothing more than const |
---|
2391 | ints, and if used in that way, I personally wouldn't consider them as |
---|
2392 | enumerations in any meaningful sense, particularly since the type checker |
---|
2393 | essentially does nothing for you there. Then they're a way of writing consts |
---|
2394 | repeatedly with some textual indicator that these definitions are related; more |
---|
2395 | namespace, less enum. |
---|
2396 | |
---|
2397 | When somebody writes bitfield members as an enum, is that *really* an |
---|
2398 | enumeration, or just a use of the syntax for enums to keep related definitions |
---|
2399 | together? |
---|
2400 | |
---|
2401 | With valediction, |
---|
2402 | - Gregor Richards |
---|
2403 | |
---|
2404 | |
---|
2405 | Date: Tue, 16 Apr 2024 11:04:51 -0400 |
---|
2406 | Subject: Re: C unnamed enumeration |
---|
2407 | To: "Peter A. Buhr" <pabuhr@uwaterloo.ca> |
---|
2408 | CC: <ajbeach@uwaterloo.ca>, <j82liang@uwaterloo.ca>, <mlbrooks@uwaterloo.ca>, |
---|
2409 | <f37yu@uwaterloo.ca> |
---|
2410 | From: Gregor Richards <gregor.richards@uwaterloo.ca> |
---|
2411 | |
---|
2412 | On 4/16/24 09:55, Peter A. Buhr wrote: |
---|
2413 | > So what is a variant? Is it a set of tag names, which might be a union or is it |
---|
2414 | > a union, which might have tag names? |
---|
2415 | |
---|
2416 | Your tagless variant bears no resemblance to variants in any functional |
---|
2417 | programming language. A variant is a tag AND a union. You might not need to put |
---|
2418 | anything in the union, in which case it's a pointless union, but the named tag |
---|
2419 | is absolutely mandatory. That's the thing that varies. |
---|
2420 | |
---|
2421 | I was unaware of std::variant. As far as functional languages are concerned, |
---|
2422 | std::variant IS NOT A VARIANT. Perhaps it would be best to use the term ADT for |
---|
2423 | the functional language concept, because that term has no other meanings. |
---|
2424 | |
---|
2425 | An ADT cannot not have a named tag. That's meaningless. The tag is the data |
---|
2426 | constructor, which is the thing you actually define when you define an ADT. It |
---|
2427 | is strictly the union that's optional. |
---|
2428 | |
---|
2429 | With valediction, |
---|
2430 | - Gregor Richards |
---|
2431 | \end{comment} |
---|
2432 | |
---|
2433 | |
---|
2434 | \section{Comparison} |
---|
2435 | |
---|
2436 | \VRef[Table]{t:FeatureLanguageComparison} shows a comparison of enumeration features and programming languages. |
---|
2437 | The features are high level and may not capture nuances within a particular language |
---|
2438 | The @const@ feature is simple macros substitution and not a typed enumeration. |
---|
2439 | |
---|
2440 | \begin{table} |
---|
2441 | \caption{Enumeration Feature / Language Comparison} |
---|
2442 | \label{t:FeatureLanguageComparison} |
---|
2443 | \small |
---|
2444 | \setlength{\tabcolsep}{3pt} |
---|
2445 | \newcommand{\CM}{\checkmark} |
---|
2446 | \begin{tabular}{r|c|c|c|c|c|c|c|c|c|c|c|c|c} |
---|
2447 | &Pascal & Ada &\Csharp& OCaml & Java &Modula-3&Golang& Rust & Swift & Python& C & \CC & \CFA \\ |
---|
2448 | \hline |
---|
2449 | @const@ & \CM & & & & & & \CM & & & & & \CM & \\ |
---|
2450 | \hline |
---|
2451 | \hline |
---|
2452 | opaque & & & & & & & & & & & & & \CM \\ |
---|
2453 | \hline |
---|
2454 | typed & & & & & & & & & & & @int@ & integral & @T@ \\ |
---|
2455 | \hline |
---|
2456 | safe & & & & & & & & & & & & \CM & \CM \\ |
---|
2457 | \hline |
---|
2458 | ordered & & & & & & & & & & & \CM & \CM & \CM \\ |
---|
2459 | \hline |
---|
2460 | dup. values & & & & & & & & & & alias & \CM & \CM & \CM \\ |
---|
2461 | \hline |
---|
2462 | setable & & & & & & & & & & & \CM & \CM & \CM \\ |
---|
2463 | \hline |
---|
2464 | auto-init & & & & & & & & & & & \CM & \CM & \CM \\ |
---|
2465 | \hline |
---|
2466 | (un)scoped & & & & & & & & & & & U & U/S & U/S \\ |
---|
2467 | \hline |
---|
2468 | overload & & \CM & & & & & & & & & & \CM & \CM \\ |
---|
2469 | \hline |
---|
2470 | switch & & & & & & & & & & & \CM & \CM & \CM \\ |
---|
2471 | \hline |
---|
2472 | loop & & & & & & & & & & & & & \CM \\ |
---|
2473 | \hline |
---|
2474 | array & & & & & & & & & & & \CM & & \CM \\ |
---|
2475 | \hline |
---|
2476 | subtype & & & & & & & & & & & & & \CM \\ |
---|
2477 | \hline |
---|
2478 | inheritance & & & & & & & & & & & & & \CM \\ |
---|
2479 | \end{tabular} |
---|
2480 | \end{table} |
---|