\chapter{Related Work} \label{s:RelatedWork} An enumeration type exist in many popular programming languages, both past and present, \eg Pascal~\cite{Pascal}, Ada~\cite{Ada}, \Csharp~\cite{Csharp}, \CC, Go~\cite{Go}, Java~\cite{Java}, Modula-3~\cite{Modula-3}, Rust~\cite{Rust}, Swift~\cite{Swift}, Python~\cite{Python}, and the algebraic data-type in functional programming. Among theses languages, there are a large set of overlapping features, but each language has its own unique extensions and restrictions. \section{Pascal} \lstnewenvironment{pascal}[1][]{% necessary \lstset{ language=pascal, escapechar=\$, % LaTeX escape in code moredelim=**[is][\color{red}]{@}{@}, % red highlighting @...@ }% lstset \lstset{#1}% necessary }{} Classic Pascal has the \lstinline[language=pascal]{const} declaration binding a name to a constant literal/expression. \begin{pascal} const one = 0 + 1; Vowels = set of (A,E,I,O,U); NULL = NIL; PI = 3.14159; Plus = '+'; Fred = 'Fred'; \end{pascal} The enumerator type is inferred from the constant-expression type. There is no notion of an ordered set, modulo the \lstinline[language=pascal]{set of} type. Free Pascal~\cite[\S~3.1.1]{FreePascal} is a modern, object-oriented version of classic Pascal, with a C-style enumeration type. Enumerators must be assigned in ascending numerical order with a constant expression and the range can be non-consecutive. \begin{pascal} Type EnumType = ( one, two, three, forty @= 40@, fortyone ); \end{pascal} Pseudo-functions @Pred@ and @Succ@ can only be used if the range is consecutive. 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. The integral size can be explicitly specified using compiler directive @$PACKENUM@~$N$, where $N$ is the number of bytes, \eg: \begin{pascal} Type @{$\color{red}\$$PACKENUM 1}@ SmallEnum = ( one, two, three ); @{$\color{red}\$$PACKENUM 4}@ LargeEnum = ( BigOne, BigTwo, BigThree ); Var S : SmallEnum; { 1 byte } L : LargeEnum; { 4 bytes} \end{pascal} \section{Ada} \lstnewenvironment{ada}[1][]{% necessary \lstset{ language=[2005]Ada, escapechar=\$, % LaTeX escape in code moredelim=**[is][\color{red}]{@}{@}, % red highlighting @...@ literate={'}{\ttfamily'\!}1 % remove '-' literate as comment }% lstset \lstset{#1}% necessary }{} An Ada enumeration type is an ordered list of constants, called \Newterm{literals} (enumerators). \begin{ada} type RGB is ( @Red@, @Green@, Blue ); -- 3 literals (enumerators) \end{ada} No other enumerators are assignable to objects of this type. Enumerators without an explicitly designated constant value are auto-initialized: from left to right, starting at zero or the next explicitly initialized constant, incrementing by 1. To explicitly set enumerator values, \emph{all} enumerators must be set in \emph{ascending} order, \ie there is no auto-initialization. \begin{ada} type RGB is ( Red, Green, Blue ); @for RGB use ( Red => 10, Green => 20, Blue => 30 );@ -- ascending order \end{ada} Hence, the position, value, label tuples are: \begin{ada} (0, 10, RED) (1, 20, GREEN) (2, 30, BLUE) \end{ada} Like C, Ada enumerators are unscoped, \ie enumerators declared inside of an enum are visible (projected) into the enclosing scope. Note, Ada is case-\emph{insensitive} so names may appear in multiple forms and still be the same name (a questionable design decision). The enumeration operators are the ordering operators, @=@, @<@, @<=@, @=@, @/=@, @>=@, @>@, where the ordering relation is given implicitly by the sequence of enumerators, which is always ascending. Ada enumerators are overloadable. \begin{ada} type Traffic_Light is ( @Red@, Yellow, @Green@ ); \end{ada} Like \CFA, Ada uses an advanced type-resolution algorithm, including the left-hand side of assignment, to disambiguate among overloaded names. \VRef[Figure]{f:AdaEnumeration} shows how ambiguity is handled using a cast, \eg \lstinline[language=ada]{RGB'(Red)}. \begin{figure} \begin{ada} with Ada.Text_IO; use Ada.Text_IO; procedure test is type RGB is ( @Red@, Green, Blue ); type Traffic_Light is ( @Red@, Yellow, Green ); -- overload procedure @Red@( Colour : RGB ) is begin -- overload Put_Line( "Colour is " & RGB'Image( Colour ) ); end Red; procedure @Red@( TL : Traffic_Light ) is begin -- overload Put_Line( "Light is " & Traffic_Light'Image( TL ) ); end Red; begin @Red@( Blue ); -- RGB @Red@( Yellow ); -- Traffic_Light @Red@( @RGB'(Red)@ ); -- ambiguous without cast end test; \end{ada} \caption{Ada Enumeration Overload Resolution} \label{f:AdaEnumeration} \end{figure} Ada provides an alias mechanism, \lstinline[language=ada]{renames}, for aliasing types, which is useful to shorten package names. \begin{ada} OtherRed : RGB renames Red; \end{ada} which suggests a possible \CFA extension to @typedef@. \begin{cfa} typedef RGB.Red OtherRed; \end{cfa} There are three pairs of inverse enumeration pseudo-functions (attributes): @'Pos@ and @'Val@, @'Enum_Rep@ and @'Enum_Val@, and @'Image@ and @'Value@, \begin{cquote} \lstDeleteShortInline@ \setlength{\tabcolsep}{15pt} \begin{tabular}{@{}ll@{}} \begin{ada} RGB'Pos( Red ) = 0; RGB'Enum_Rep( Red ) = 10; RGB'Image( Red ) = "RED"; \end{ada} & \begin{ada} RGB'Val( 0 ) = Red RGB'Enum_Val( 10 ) = Red RGB'Value( "Red" ) = Red \end{ada} \end{tabular} \lstMakeShortInline@ \end{cquote} These attributes are important for IO. 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. Ada allows the enumerator label to be a character constant. \begin{ada} type Operator is ( '+', '-', '*', '/' ); Op : Operator; \end{ada} which is syntactic sugar for the label and not character literals from the predefined type @Character@. The purpose is readability using character literals rather than names. \begin{ada} Op := '+'; case Op is -- all enumerators must appear when '+' => ... ; when '-' => ... ; when '*' => ... ; when '/' => ... ; end case; \end{ada} Arrays of character enumerators can be treated as strings. \begin{ada} Ops : array( 0..3 ) of Operator; Ops := @"+-*/"@; -- string assignment to array elements Ops := @"+-" & "*/"@; -- string concatenation and assignment for Op of Ops loop Put_Line( Operator'Image( Op ) ); end loop; \end{ada} Ada's @Character@ type is defined as a character enumeration across all Latin-1 characters. Ada's boolean type is defined as a special enumeration, which can be used in conditions. \begin{ada} type Boolean is (False, True); -- False / True not keywords @Flag@ : Boolean; if @Flag@ then ... -- conditional \end{ada} Since only types derived from @Boolean@ can be a conditional, @Boolean@ is essentially a builtin type. Ada provides \emph{consecutive} subtyping of an enumeration using \lstinline[language=ada]{range}. \begin{ada} type Week is ( Mon, Tue, Wed, Thu, Fri, Sat, Sun ); subtype Weekday is Week @range Mon .. Fri@; subtype Weekend is Week @range Sat .. Sun@; Day : Week; \end{ada} Hence, the ordering of the enumerators is crucial to provide the necessary ranges. An enumeration type can be used in the Ada \lstinline[language=ada]{case} (switch) and iterating constructs. \begin{cquote} \lstDeleteShortInline@ \setlength{\tabcolsep}{15pt} \begin{tabular}{@{}ll@{}} \begin{ada} case Day is when @Mon .. Fri@ => ... ; when @Sat .. Sun@ => ... ; end case; \end{ada} & \begin{ada} case Day is when @Weekday@ => ... ; -- subtype ranges when @Weekend@ => ... ; end case; \end{ada} \end{tabular} \end{cquote} \begin{cquote} \setlength{\tabcolsep}{12pt} \begin{tabular}{@{}lll@{}} \begin{ada} for Day in @Mon .. Sun@ loop ... end loop; \end{ada} & \begin{ada} for Day in @Weekday@ loop ... end loop; \end{ada} & \begin{ada} for Day in @Weekend@ loop ... end loop; \end{ada} \end{tabular} \lstMakeShortInline@ \end{cquote} An enumeration type can be used as an array dimension and subscript. \begin{ada} Lunch : array( @Week@ ) of Time; for Day in Week loop Lunch( @Day@ ) := ... ; -- set lunch time end loop; \end{ada} \section{\CC} \label{s:C++RelatedWork} \lstnewenvironment{c++}[1][]{% necessary \lstset{ language=[GNU]C++, escapechar=\$, % LaTeX escape in code moredelim=**[is][\color{red}]{@}{@}, % red highlighting @...@ }% lstset \lstset{#1}% necessary }{} \CC is largely backwards compatible with C, so it inherited C's enumerations. However, the following non-backwards compatible changes have been made. \begin{cquote} 7.2 Change: \CC objects of enumeration type can only be assigned values of the same enumeration type. In C, objects of enumeration type can be assigned values of any integral type. \\ Example: \begin{c++} enum color { red, blue, green }; color c = 1; $\C{// valid C, invalid C++}$ \end{c++} \textbf{Rationale}: The type-safe nature of \CC. \\ \textbf{Effect on original feature}: Deletion of semantically well-defined feature. \\ \textbf{Difficulty of converting}: Syntactic transformation. (The type error produced by the assignment can be automatically corrected by applying an explicit cast.) \\ \textbf{How widely used}: Common. \end{cquote} \begin{cquote} 7.2 Change: In \CC, the type of an enumerator is its enumeration. In C, the type of an enumerator is @int@. \\ Example: \begin{c++} enum e { A }; sizeof(A) == sizeof(int) $\C{// in C}$ sizeof(A) == sizeof(e) $\C{// in C++}$ /* and sizeof(int) is not necessary equal to sizeof(e) */ \end{c++} \textbf{Rationale}: In \CC, an enumeration is a distinct type. \\ \textbf{Effect on original feature}: Change to semantics of well-defined feature. \\ \textbf{Difficulty of converting}: Semantic transformation. \\ \textbf{How widely used}: Seldom. The only time this affects existing C code is when the size of an enumerator is taken. Taking the size of an enumerator is not a common C coding practice. \end{cquote} Hence, the values in a \CC enumeration can only be its enumerators (without a cast). While the storage size of an enumerator is up to the compiler, there is still an implicit cast to @int@. \begin{c++} enum E { A, B, C }; E e = A; int i = A; i = e; $\C{// implicit casts to int}$ \end{c++} \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. \begin{c++} enum class E { A, B, C }; E e = @E::@A; $\C{// qualified enumerator}$ e = B; $\C{// B not in scope}$ \end{c++} \CC{20} supports explicit unscoping with a \lstinline[language=c++]{using enum} declaration. \begin{c++} enum class E { A, B, C }; @using enum E;@ E e = A; $\C{// direct access}$ e = B; $\C{// direct access}$ \end{c++} \CC{11} added the ability to explicitly declare the underlying \emph{integral} type for \lstinline[language=c++]{enum class}. \begin{c++} enum class RGB @: long@ { Red, Green, Blue }; enum class rgb @: char@ { Red = 'r', Green = 'g', Blue = 'b' }; enum class srgb @: signed char@ { Red = -1, Green = 0, Blue = 1 }; \end{c++} There is no implicit conversion from the \lstinline[language=c++]{enum class} type and to its type. \begin{c++} rgb crgb = rgb::Red; char ch = rgb::Red; ch = crgb; $\C{// disallowed}$ \end{c++} Finally, there is no mechanism to iterate through an enumeration nor use the enumeration type to declare an array dimension. \section{C\raisebox{-0.7ex}{\LARGE$^\sharp$}\xspace} % latex bug: cannot use \relsize{2} so use \LARGE \lstnewenvironment{csharp}[1][]{% necessary \lstset{ language=[Sharp]C, escapechar=\$, % LaTeX escape in code moredelim=**[is][\color{red}]{@}{@}, % red highlighting @...@ }% lstset \lstset{#1}% necessary }{} % https://www.tutorialsteacher.com/codeeditor?cid=cs-mk8Ojx \Csharp is a dynamically-typed programming-language with a scoped, integral enumeration-type similar to C/\CC enumeration. \begin{csharp} enum Weekday : byte { Monday, Tuesday, Wednesday, Thursday@ = 10@, Friday, Saturday, Sunday@,@ }; \end{csharp} The default underlying type is @int@, with auto-incrementing, implicit/explicit initialization, terminator comma, and optional integral typing (default @int@) A method cannot be defined in an enumeration type. 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. \begin{csharp} int day = (int)Weekday.Friday; $\C{// day == 10}$ Weekday weekday = (Weekdays)42; $\C{// weekday == 42}$ Console.WriteLine( Weekday.Friday ); $\C{// print Friday}$ string mon = Weekday.Monday.ToString(); \end{csharp} The @Enum.GetValues@ pseudo-method retrieves an array of the enumeration constants for looping over an enumeration type or variable. \begin{csharp} foreach ( Weekday constant in @Enum.GetValues@( typeof(Weekday) ) ) { Console.WriteLine( constant + " " + (int)constant ); // label, position } \end{csharp} The @Flags@ attribute creates a bit-flags enumeration, allowing bitwise operators @&@, @|@, @~@ (complement), @^@ (xor). \begin{csharp} @[Flags]@ public enum Weekday { None = 0x0, Monday = 0x1, Tuesday = 0x2, Wednesday = 0x4, Thursday = 0x8, Friday = 0x10, Saturday = 0x20, Sunday = 0x40, Weekend = @Saturday | Sunday@, Weekdays = @Monday | Tuesday | Wednesday | Thursday | Friday@ } Weekday meetings = @Weekday.Monday | Weekday.Wednesday@; // 0x5 \end{csharp} \Csharp supports an enumeration class to embed enumeration operations, where the enumerators are objects. \begin{csharp} public class PaymentType : Enumeration { public static readonly PaymentType DebitCard = new PaymentType(0); public static readonly PaymentType CreditCard = new PaymentType(1); private PaymentType(int value, [CallerMemberName] string name = null) : base(value, name) { } } \end{csharp} Find a meaningful example and test it. \section{Golang} \lstnewenvironment{Go}[1][]{% necessary \lstset{ language=Go, escapechar=\$, % LaTeX escape in code moredelim=**[is][\color{red}]{@}{@}, % red highlighting @...@ }% lstset \lstset{#1}% necessary }{} The Golang enumeration is similar to classic Pascal \lstinline[language=pascal]{const}, binding a name to a constant literal/expression. \begin{Go} const ( R = 0; G; B ) $\C{// implicit: 0 0 0}$ const ( Fred = "Fred"; Mary = "Mary"; Jane = "Jane" ) $\C{// explicit: Fred Mary Jane}$ const ( S = 0; T; USA = "USA"; U; V = 3.1; W ) $\C{// type change, implicit/explicit: 0 0 USA USA 3.1 3.1}$ \end{Go} Constant names are unscoped and must be unique (no overloading). The first enumerator \emph{must} be explicitly initialized; subsequent enumerators can be implicitly or explicitly initialized. Implicit initialization is the previous (predecessor) enumerator value. Auto-incrementing is supported by the keyword \lstinline[language=Go]{iota}, available only in the \lstinline[language=Go]{const} declaration. 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). \begin{Go} const ( R = @iota@; G; B ) $\C{// implicit: 0 1 2}$ const ( C = @iota + B + 1@; G; Y ) $\C{// implicit: 3 4 5}$ \end{Go} An underscore \lstinline[language=golang]{const} identifier advances \lstinline[language=Go]{iota}. \begin{Go} const ( O1 = iota + 1; @_@; O3; @_@; O5 ) // 1, 3, 5 \end{Go} Auto-incrementing stops after an explicit initialization. \begin{Go} const ( Monday = iota; Tuesday; Wednesday; // 0, 1, 2 @Thursday = 10@; Friday; Saturday; Sunday ) // 10, 10, 10, 10 \end{Go} Auto-incrementing can be restarted with an expression containing \emph{one} \lstinline[language=Go]{iota}. \begin{Go} const ( V1 = iota; V2; @V3 = 7;@ V4 = @iota@; V5 ) // 0 1 7 3 4 const ( Monday = iota; Tuesday; Wednesday; // 0, 1, 2 @Thursday = 10;@ Friday = @iota - Wednesday + Thursday - 1@; Saturday; Sunday ) // 10, 11, 12, 13 \end{Go} Note, \lstinline[language=Go]{iota} is advanced for an explicitly initialized enumerator, like the underscore @_@ identifier. \section{Java} \lstnewenvironment{Java}[1][]{% necessary \lstset{ language=Java, escapechar=\$, % LaTeX escape in code moredelim=**[is][\color{red}]{`}{`}, % red highlighting @...@ }% lstset \lstset{#1}% necessary }{} Here's a quick and simple example of an enum that defines the status of a pizza order; the order status can be ORDERED, READY or DELIVERED: \begin{Java} public enum PizzaStatus { ORDERED, READY, DELIVERED; } \end{Java} Additionally, enums come with many useful methods that we would otherwise need to write if we were using traditional public static final constants. \paragraph{Custom Enum Methods} Now that we have a basic understanding of what enums are and how we can use them, we'll take our previous example to the next level by defining some extra API methods on the enum: \begin{Java} public class Pizza { private PizzaStatus status; public enum PizzaStatus { ORDERED, READY, DELIVERED; } public boolean isDeliverable() { if (getStatus() == PizzaStatus.READY) { return true; } return false; } // Methods that set and get the status variable. } \end{Java} \paragraph{Comparing Enum Types Using "==" Operator} Since enum types ensure that only one instance of the constants exist in the JVM, we can safely use the "==" operator to compare two variables, like we did in the above example. Furthermore, the "==" operator provides compile-time and run-time safety. First, we'll look at run-time safety in the following snippet, where we'll use the "==" operator to compare statuses. Either value can be null and we won't get a NullPointerException. Conversely, if we use the equals method, we will get a NullPointerException: \begin{Java} if(testPz.getStatus().equals(Pizza.PizzaStatus.DELIVERED)); if(testPz.getStatus() == Pizza.PizzaStatus.DELIVERED); \end{Java} As for compile-time safety, let's look at an example where we'll determine that an enum of a different type is equal by comparing it using the equals method. This is because the values of the enum and the getStatus method coincidentally are the same; however, logically the comparison should be false. We avoid this issue by using the "==" operator. The compiler will flag the comparison as an incompatibility error: \begin{Java} if(testPz.getStatus().equals(TestColor.GREEN)); if(testPz.getStatus() == TestColor.GREEN); \end{Java} \paragraph{Using Enum Types in Switch Statements} We can use enum types in switch statements also: \begin{Java} public int getDeliveryTimeInDays() { switch (status) { case ORDERED: return 5; case READY: return 2; case DELIVERED: return 0; } return 0; } \end{Java} \paragraph{Fields, Methods and Constructors in Enums} We can define constructors, methods, and fields inside enum types, which makes them very powerful. Next, let's extend the example above by implementing the transition from one stage of a pizza order to another. We'll see how we can get rid of the if and switch statements used before: \begin{Java} public class Pizza { private PizzaStatus status; public enum PizzaStatus { ORDERED (5){ @Override public boolean isOrdered() { return true; } }, READY (2){ @Override public boolean isReady() { return true; } }, DELIVERED (0){ @Override public boolean isDelivered() { return true; } }; private int timeToDelivery; public boolean isOrdered() {return false;} public boolean isReady() {return false;} public boolean isDelivered(){return false;} public int getTimeToDelivery() { return timeToDelivery; } PizzaStatus (int timeToDelivery) { this.timeToDelivery = timeToDelivery; } } public boolean isDeliverable() { return this.status.isReady(); } public void printTimeToDeliver() { System.out.println("Time to delivery is " + this.getStatus().getTimeToDelivery()); } // Methods that set and get the status variable. } \end{Java} The test snippet below demonstrates how this works: \begin{Java} @Test public void givenPizaOrder_whenReady_thenDeliverable() { Pizza testPz = new Pizza(); testPz.setStatus(Pizza.PizzaStatus.READY); assertTrue(testPz.isDeliverable()); } \end{Java} \paragraph{EnumSet and EnumMap} \paragraph{EnumSet} The EnumSet is a specialized Set implementation that's meant to be used with Enum types. Compared to a HashSet, it's a very efficient and compact representation of a particular Set of Enum constants, owing to the internal Bit Vector Representation that's used. It also provides a type-safe alternative to traditional int-based "bit flags," allowing us to write concise code that's more readable and maintainable. The EnumSet is an abstract class that has two implementations, RegularEnumSet and JumboEnumSet, one of which is chosen depending on the number of constants in the enum at the time of instantiation. Therefore, it's a good idea to use this set whenever we want to work with a collection of enum constants in most scenarios (like subsetting, adding, removing, and bulk operations like containsAll and removeAll), and use Enum.values() if we just want to iterate over all possible constants. In the code snippet below, we can see how to use EnumSet to create a subset of constants: \begin{Java} public class Pizza { private static EnumSet undeliveredPizzaStatuses = EnumSet.of(PizzaStatus.ORDERED, PizzaStatus.READY); private PizzaStatus status; public enum PizzaStatus { ... } public boolean isDeliverable() { return this.status.isReady(); } public void printTimeToDeliver() { System.out.println("Time to delivery is " + this.getStatus().getTimeToDelivery() + " days"); } public static List getAllUndeliveredPizzas(List input) { return input.stream().filter( (s) -> undeliveredPizzaStatuses.contains(s.getStatus())) .collect(Collectors.toList()); } public void deliver() { if (isDeliverable()) { PizzaDeliverySystemConfiguration.getInstance().getDeliveryStrategy() .deliver(this); this.setStatus(PizzaStatus.DELIVERED); } } // Methods that set and get the status variable. } \end{Java} Executing the following test demonstrates the power of the EnumSet implementation of the Set interface: \begin{Java} @Test public void givenPizaOrders_whenRetrievingUnDeliveredPzs_thenCorrectlyRetrieved() { List pzList = new ArrayList<>(); Pizza pz1 = new Pizza(); pz1.setStatus(Pizza.PizzaStatus.DELIVERED); Pizza pz2 = new Pizza(); pz2.setStatus(Pizza.PizzaStatus.ORDERED); Pizza pz3 = new Pizza(); pz3.setStatus(Pizza.PizzaStatus.ORDERED); Pizza pz4 = new Pizza(); pz4.setStatus(Pizza.PizzaStatus.READY); pzList.add(pz1); pzList.add(pz2); pzList.add(pz3); pzList.add(pz4); List undeliveredPzs = Pizza.getAllUndeliveredPizzas(pzList); assertTrue(undeliveredPzs.size() == 3); } \end{Java} \paragraph{EnumMap} EnumMap is a specialized Map implementation meant to be used with enum constants as keys. Compared to its counterpart HashMap, it's an efficient and compact implementation that's internally represented as an array: \begin{Java} EnumMap map; \end{Java} Let's look at an example of how we can use it in practice: \begin{Java} public static EnumMap> groupPizzaByStatus(List pizzaList) { EnumMap> pzByStatus = new EnumMap>(PizzaStatus.class); for (Pizza pz : pizzaList) { PizzaStatus status = pz.getStatus(); if (pzByStatus.containsKey(status)) { pzByStatus.get(status).add(pz); } else { List newPzList = new ArrayList(); newPzList.add(pz); pzByStatus.put(status, newPzList); } } return pzByStatus; } \end{Java} Executing the following test demonstrates the power of the EnumMap implementation of the Map interface: \begin{Java} @Test public void givenPizaOrders_whenGroupByStatusCalled_thenCorrectlyGrouped() { List pzList = new ArrayList<>(); Pizza pz1 = new Pizza(); pz1.setStatus(Pizza.PizzaStatus.DELIVERED); Pizza pz2 = new Pizza(); pz2.setStatus(Pizza.PizzaStatus.ORDERED); Pizza pz3 = new Pizza(); pz3.setStatus(Pizza.PizzaStatus.ORDERED); Pizza pz4 = new Pizza(); pz4.setStatus(Pizza.PizzaStatus.READY); pzList.add(pz1); pzList.add(pz2); pzList.add(pz3); pzList.add(pz4); EnumMap> map = Pizza.groupPizzaByStatus(pzList); assertTrue(map.get(Pizza.PizzaStatus.DELIVERED).size() == 1); assertTrue(map.get(Pizza.PizzaStatus.ORDERED).size() == 2); assertTrue(map.get(Pizza.PizzaStatus.READY).size() == 1); } \end{Java} \paragraph{Singleton Pattern} Normally, implementing a class using the Singleton pattern is quite non-trivial. Enums provide a quick and easy way of implementing singletons. In addition, since the enum class implements the Serializable interface under the hood, the class is guaranteed to be a singleton by the JVM. This is unlike the conventional implementation, where we have to ensure that no new instances are created during deserialization. In the code snippet below, we see how we can implement a singleton pattern: \begin{Java} public enum PizzaDeliverySystemConfiguration { INSTANCE; PizzaDeliverySystemConfiguration() { // Initialization configuration which involves // overriding defaults like delivery strategy } private PizzaDeliveryStrategy deliveryStrategy = PizzaDeliveryStrategy.NORMAL; public static PizzaDeliverySystemConfiguration getInstance() { return INSTANCE; } public PizzaDeliveryStrategy getDeliveryStrategy() { return deliveryStrategy; } } \end{Java} \paragraph{Strategy Pattern} Conventionally, the Strategy pattern is written by having an interface that is implemented by different classes. Adding a new strategy means adding a new implementation class. With enums, we can achieve this with less effort, and adding a new implementation means simply defining another instance with some implementation. The code snippet below shows how to implement the Strategy pattern: \begin{Java} public enum PizzaDeliveryStrategy { EXPRESS { @Override public void deliver(Pizza pz) { System.out.println("Pizza will be delivered in express mode"); } }, NORMAL { @Override public void deliver(Pizza pz) { System.out.println("Pizza will be delivered in normal mode"); } }; public abstract void deliver(Pizza pz); } \end{Java} Then we add the following method to the Pizza class: \begin{Java} public void deliver() { if (isDeliverable()) { PizzaDeliverySystemConfiguration.getInstance().getDeliveryStrategy() .deliver(this); this.setStatus(PizzaStatus.DELIVERED); } } @Test public void givenPizaOrder_whenDelivered_thenPizzaGetsDeliveredAndStatusChanges() { Pizza pz = new Pizza(); pz.setStatus(Pizza.PizzaStatus.READY); pz.deliver(); assertTrue(pz.getStatus() == Pizza.PizzaStatus.DELIVERED); } \end{Java} 8. Java 8 and Enums We can rewrite the Pizza class in Java 8, and see how the methods getAllUndeliveredPizzas() and groupPizzaByStatus() become so concise with the use of lambdas and the Stream APIs: \begin{Java} public static List getAllUndeliveredPizzas(List input) { return input.stream().filter( (s) -> !deliveredPizzaStatuses.contains(s.getStatus())) .collect(Collectors.toList()); } public static EnumMap> groupPizzaByStatus(List pzList) { EnumMap> map = pzList.stream().collect( Collectors.groupingBy(Pizza::getStatus, () -> new EnumMap<>(PizzaStatus.class), Collectors.toList())); return map; } \end{Java} \section{Modula-3} \section{Rust} \section{Swift} \lstnewenvironment{swift}[1][]{% necessary \lstset{ language=Swift, escapechar=\$, % LaTeX escape in code moredelim=**[is][\color{red}]{@}{@}, % red highlighting @...@ }% lstset \lstset{#1}% necessary }{} Model custom types that define a list of possible values. 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. If you are familiar with C, you will know that C enumerations assign related names to a set of integer values. Enumerations in Swift are much more flexible, and don't have to provide a value for each case of the enumeration. 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. 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. 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. Enumerations in Swift are first-class types in their own right. 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. Enumerations can also define initializers to provide an initial case value; can be extended to expand their functionality beyond their original implementation; and can conform to protocols to provide standard functionality. For more about these capabilities, see Properties, Methods, Initialization, Extensions, and Protocols. \paragraph{Enumeration Syntax} You introduce enumerations with the @enum@ keyword and place their entire definition within a pair of braces: \begin{swift} enum SomeEnumeration { // enumeration definition goes here } \end{swift} Here's an example for the four main points of a compass: \begin{swift} enum CompassPoint { case north case south case east case west } \end{swift} The values defined in an enumeration (such as @north@, @south@, @east@, and @west@) are its enumeration cases. You use the @case@ keyword to introduce new enumeration cases. Note: Swift enumeration cases don't have an integer value set by default, unlike languages like C and Objective-C. In the CompassPoint example above, @north@, @south@, @east@ and @west@ don't implicitly equal 0, 1, 2 and 3. Instead, the different enumeration cases are values in their own right, with an explicitly defined type of CompassPoint. Multiple cases can appear on a single line, separated by commas: \begin{swift} enum Planet { case mercury, venus, earth, mars, jupiter, saturn, uranus, neptune } \end{swift} Each enumeration definition defines a new type. Like other types in Swift, their names (such as @CompassPoint@ and @Planet@) start with a capital letter. Give enumeration types singular rather than plural names, so that they read as self-evident: \begin{swift} var directionToHead = CompassPoint.west \end{swift} The type of @directionToHead@ is inferred when it's initialized with one of the possible values of @CompassPoint@. Once @directionToHead@ is declared as a @CompassPoint@, you can set it to a different @CompassPoint@ value using a shorter dot syntax: \begin{swift} directionToHead = .east \end{swift} The type of @directionToHead@ is already known, and so you can drop the type when setting its value. This makes for highly readable code when working with explicitly typed enumeration values. \paragraph{Matching Enumeration Values with a Switch Statement} You can match individual enumeration values with a switch statement: \begin{swift} directionToHead = .south switch directionToHead { case .north: print("Lots of planets have a north") case .south: print("Watch out for penguins") case .east: print("Where the sun rises") case .west: print("Where the skies are blue") } // Prints "Watch out for penguins" \end{swift} You can read this code as: \begin{quote} "Consider the value of directionToHead. In the case where it equals @.north@, print "Lots of planets have a north". In the case where it equals @.south@, print "Watch out for penguins"." ...and so on. \end{quote} As described in Control Flow, a switch statement must be exhaustive when considering an enumeration's cases. If the case for @.west@ is omitted, this code doesn't compile, because it doesn't consider the complete list of @CompassPoint@ cases. Requiring exhaustiveness ensures that enumeration cases aren't accidentally omitted. 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: \begin{swift} let somePlanet = Planet.earth switch somePlanet { case .earth: print("Mostly harmless") default: print("Not a safe place for humans") } // Prints "Mostly harmless" \end{swift} \paragraph{Iterating over Enumeration Cases} For some enumerations, it's useful to have a collection of all of that enumeration's cases. You enable this by writing @CaseIterable@ after the enumeration's name. Swift exposes a collection of all the cases as an allCases property of the enumeration type. Here's an example: \begin{swift} enum Beverage: CaseIterable { case coffee, tea, juice } let numberOfChoices = Beverage.allCases.count print("\(numberOfChoices) beverages available") // Prints "3 beverages available" \end{swift} In the example above, you write @Beverage.allCases@ to access a collection that contains all of the cases of the @Beverage@ enumeration. 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. The example above counts how many cases there are, and the example below uses a for-in loop to iterate over all the cases. \begin{swift} for beverage in Beverage.allCases { print(beverage) } // coffee // tea // juice \end{swift} The syntax used in the examples above marks the enumeration as conforming to the @CaseIterable@ protocol. For information about protocols, see Protocols. \paragraph{Associated Values} The examples in the previous section show how the cases of an enumeration are a defined (and typed) value in their own right. You can set a constant or variable to Planet.earth, and check for this value later. However, it's sometimes useful to be able to store values of other types alongside these case values. This additional information is called an associated value, and it varies each time you use that case as a value in your code. 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. Enumerations similar to these are known as discriminated unions, tagged unions, or variants in other programming languages. For example, suppose an inventory tracking system needs to track products by two different types of barcode. Some products are labeled with 1D barcodes in UPC format, which uses the numbers 0 to 9. Each barcode has a number system digit, followed by five manufacturer code digits and five product code digits. These are followed by a check digit to verify that the code has been scanned correctly: 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: 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. In Swift, an enumeration to define product barcodes of either type might look like this: \begin{swift} enum Barcode { case upc(Int, Int, Int, Int) case qrCode(String) } \end{swift} This can be read as: \begin{quote} "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@." \end{quote} 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@. You can then create new barcodes using either type: \begin{swift} var productBarcode = Barcode.upc(8, 85909, 51226, 3) \end{swift} 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)@. You can assign the same product a different type of barcode: \begin{swift} productBarcode = .qrCode("ABCDEFGHIJKLMNOP") \end{swift} At this point, the original @Barcode.upc@ and its integer values are replaced by the new @Barcode.qrCode@ and its string value. 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. You can check the different barcode types using a switch statement, similar to the example in Matching Enumeration Values with a Switch Statement. This time, however, the associated values are extracted as part of the switch statement. 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: \begin{swift} switch productBarcode { case .upc(let numberSystem, let manufacturer, let product, let check): print("UPC: \(numberSystem), \(manufacturer), \(product), \(check).") case .qrCode(let productCode): print("QR code: \(productCode).") } // Prints "QR code: ABCDEFGHIJKLMNOP." \end{swift} 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: \begin{swift} switch productBarcode { case let .upc(numberSystem, manufacturer, product, check): print("UPC : \(numberSystem), \(manufacturer), \(product), \(check).") case let .qrCode(productCode): print("QR code: \(productCode).") } // Prints "QR code: ABCDEFGHIJKLMNOP." \end{swift} \paragraph{Raw Values} The barcode example in Associated Values shows how cases of an enumeration can declare that they store associated values of different types. As an alternative to associated values, enumeration cases can come prepopulated with default values (called raw values), which are all of the same type. Here's an example that stores raw ASCII values alongside named enumeration cases: \begin{swift} enum ASCIIControlCharacter: Character { case tab = "\t" case lineFeed = "\n" case carriageReturn = "\r" } \end{swift} 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. Character values are described in Strings and Characters. Raw values can be strings, characters, or any of the integer or floating-point number types. Each raw value must be unique within its enumeration declaration. Note Raw values are not the same as associated values. Raw values are set to prepopulated values when you first define the enumeration in your code, like the three ASCII codes above. The raw value for a particular enumeration case is always the same. 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. Implicitly Assigned Raw Values 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. When you don't, Swift automatically assigns the values for you. For example, when integers are used for raw values, the implicit value for each case is one more than the previous case. If the first case doesn't have a value set, its value is 0. The enumeration below is a refinement of the earlier Planet enumeration, with integer raw values to represent each planet's order from the sun: \begin{swift} enum Planet: Int { case mercury = 1, venus, earth, mars, jupiter, saturn, uranus, neptune } \end{swift} 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. When strings are used for raw values, the implicit value for each case is the text of that case's name. The enumeration below is a refinement of the earlier CompassPoint enumeration, with string raw values to represent each direction's name: \begin{swift} enum CompassPoint: String { case north, south, east, west } \end{swift} In the example above, CompassPoint.south has an implicit raw value of "south", and so on. You access the raw value of an enumeration case with its rawValue property: \begin{swift} let earthsOrder = Planet.earth.rawValue // earthsOrder is 3 let sunsetDirection = CompassPoint.west.rawValue // sunsetDirection is "west" \end{swift} \paragraph{Initializing from a Raw Value} 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. You can use this initializer to try to create a new instance of the enumeration. This example identifies Uranus from its raw value of 7: \begin{swift} let possiblePlanet = Planet(rawValue: 7) // possiblePlanet is of type Planet? and equals Planet.uranus \end{swift} Not all possible Int values will find a matching planet, however. Because of this, the raw value initializer always returns an optional enumeration case. In the example above, possiblePlanet is of type Planet?, or "optional Planet." Note The raw value initializer is a failable initializer, because not every raw value will return an enumeration case. For more information, see Failable Initializers. 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: \begin{swift} let positionToFind = 11 if let somePlanet = Planet(rawValue: positionToFind) { switch somePlanet { case .earth: print("Mostly harmless") default: print("Not a safe place for humans") } } else { print("There isn't a planet at position \(positionToFind)") } // Prints "There isn't a planet at position 11" \end{swift} This example uses optional binding to try to access a planet with a raw value of 11. 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. In this case, it isn't possible to retrieve a planet with a position of 11, and so the else branch is executed instead. \paragraph{Recursive Enumerations} 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. You indicate that an enumeration case is recursive by writing indirect before it, which tells the compiler to insert the necessary layer of indirection. For example, here is an enumeration that stores simple arithmetic expressions: \begin{swift} enum ArithmeticExpression { case number(Int) indirect case addition(ArithmeticExpression, ArithmeticExpression) indirect case multiplication(ArithmeticExpression, ArithmeticExpression) } \end{swift} 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: \begin{swift} indirect enum ArithmeticExpression { case number(Int) case addition(ArithmeticExpression, ArithmeticExpression) case multiplication(ArithmeticExpression, ArithmeticExpression) } \end{swift} This enumeration can store three kinds of arithmetic expressions: a plain number, the addition of two expressions, and the multiplication of two expressions. The addition and multiplication cases have associated values that are also arithmetic expressions -- these associated values make it possible to nest expressions. 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. 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. The code below shows the ArithmeticExpression recursive enumeration being created for (5 + 4) * 2: \begin{swift} let five = ArithmeticExpression.number(5) let four = ArithmeticExpression.number(4) let sum = ArithmeticExpression.addition(five, four) let product = ArithmeticExpression.multiplication(sum, ArithmeticExpression.number(2)) \end{swift} A recursive function is a straightforward way to work with data that has a recursive structure. For example, here's a function that evaluates an arithmetic expression: \begin{swift} func evaluate(_ expression: ArithmeticExpression) -> Int { switch expression { case let .number(value): return value case let .addition(left, right): return evaluate(left) + evaluate(right) case let .multiplication(left, right): return evaluate(left) * evaluate(right) } } print(evaluate(product)) // Prints "18" \end{swift} This function evaluates a plain number by simply returning the associated value. 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. \section{Python} \section{Algebraic Data Type}