Index: doc/theses/jiada_liang_MMath/background.tex
===================================================================
--- doc/theses/jiada_liang_MMath/background.tex	(revision 38f5006ef2bee7ba7cdf8bc8ef954804e0243166)
+++ doc/theses/jiada_liang_MMath/background.tex	(revision 7bb516f9dde25f48bb6a37546feafba084354c29)
@@ -27,5 +27,5 @@
 In theory, a C enumeration \emph{variable} is an implementation-defined integral type large enough to hold all enumerated values.
 In practice, since integral constants are used, which have type @int@ (unless qualified with a size suffix), C uses @int@ as the underlying type for enumeration variables.
-Finally, there is an implicit bidirectional conversion between an enumeration and integral types.
+Finally, there is an implicit bidirectional conversion between an enumeration and its integral type.
 \begin{cfa}
 {
Index: doc/theses/jiada_liang_MMath/implementation.tex
===================================================================
--- doc/theses/jiada_liang_MMath/implementation.tex	(revision 38f5006ef2bee7ba7cdf8bc8ef954804e0243166)
+++ doc/theses/jiada_liang_MMath/implementation.tex	(revision 7bb516f9dde25f48bb6a37546feafba084354c29)
@@ -253,56 +253,60 @@
 
 \section{Enumerator Initialization}
+
 An enumerator must have a deterministic immutable value, either be explicitly initialized in the enumeration definition, or implicitly initialized by rules.
 
+
 \section{C Enumeration Rule}
+
 A C enumeration has an integral type. If not initialized, the first enumerator implicitly has the integral value 0, and other enumerators have a value equal to its $predecessor + 1$.
 
-\section{Auto Initializable}
-\label{s:AutoInitializable}
-
-
-\CFA enumerations have the same rule in enumeration constant initialization.
-However, only \CFA types that have defined traits for @zero_t@, @one_t@, and an addition operator can be automatically initialized by \CFA.
-
-Specifically, a type is auto-initializable only if it satisfies the trait @AutoInitializable@:
-\begin{cfa}
-forall(T)
-trait AutoInitializable {
-	void ?()( T & t, zero_t );
-	S ?++( T & t);
-};
-\end{cfa}
-An example of a user-defined @AutoInitializable@ is:
-\begin{cfa}[label=lst:sample_auto_Initializable]
-struct Odd { int i; };
-void ?()( Odd & t, zero_t ) { t.i = 1; };
-Odd ?++( Odd t1 ) { return Odd( t1.i + 2); };
-\end{cfa}
-When the type of an enumeration is @AutoInitializable@, implicit initialization is available.
-\begin{cfa}[label=lst:sample_auto_Initializable_usage]
-enum AutoInitUsage(Odd) {
-	A, B, C = 7, D
-};
-\end{cfa}
-In the example, no initializer is specified for the first enumeration constant @A@, so \CFA initializes it with the value of @zero_t@, which is 1.
-@B@ and @D@ have the values of their $predecessor++$, where @one_t@ has the value 2.
-Therefore, the enumeration is initialized as follows:
-\begin{cfa}[label=lst:sample_auto_Initializable_usage_gen]
-enum AutoInitUsage(Odd) {
-	A = 1, B = 3, C = 7, D = 9
-};
-\end{cfa}
-Note that there is no mechanism to prevent an even value for the direct initialization, such as @C = 6@.
-
-In \CFA, character, integral, float, and imaginary types are all @AutoInitialiable@.
-\begin{cfa}[label=lst:letter]
-enum Alphabet( int ) {
+
+\section{Auto Initialization}
+
+C auto-initialization works for the integral type @int@ with constant expressions.
+\begin{cfa}
+enum Alphabet ! {
 	A = 'A', B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z,
 	a = 'a', b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z
 };
-print( "%c, %c, %c", Alphabet.F, Alphabet.o, Alphabet.z );
->>> F, o, z
-\end{cfa}
+\end{cfa}
+The complexity of the constant expression depends on the level of runtime computation the compiler implements, \eg \CC \lstinline[language={[GNU]C++}]{constexpr} provides complex compile-time computation across multiple types, which blurs the compilation/runtime boundary.
+
+The notion of auto-initialization can be generalized in \CFA through the trait @AutoInitializable@.
+\begin{cfa}
+forall(T) @trait@ AutoInitializable {
+	void ?{}( T & o, T v );				$\C{// initialization}$
+	void ?{}( T & t, zero_t );			$\C{// 0}$
+	T ?++( T & t);						$\C{// increment}$
+};
+\end{cfa}
+In addition, there is an implicit enumeration counter, @ecnt@ of type @T@, managed by the compiler.
+For example, the type @Odd@ satisfies @AutoInitializable@:
+\begin{cfa}
+struct Odd { int i; };
+void ?{}( Odd & o, int v ) { if ( v & 1 ) o.i = v; else /* error not odd */ ; };
+void ?{}( Odd & o, zero_t ) { o.i = 1; };
+Odd ?++( Odd o ) { return (Odd){ o.i + 2 }; };
+\end{cfa}
+and implicit initialization is available.
+\begin{cfa}
+enum( Odd ) { A, B, C = 7, D };			$\C{// 1, 3, 7, 9}$
+\end{cfa}
+where the compiler performs the following transformation and runs the code.
+\begin{cfa}
+enum( Odd ) {
+	?{}( ecnt, @0@ }  ?{}( A, ecnt },	?++( ecnt )  ?{}( B, ecnt ),
+	?{}( ecnt, 7 )  ?{}( C, ecnt ),	?++( ecnt )  ?{}( D, ecnt )
+};
+\end{cfa}
+
+Unfortunately, auto-initialization is not implemented because \CFA is only a transpiler, relying on generated C code to perform the detail work.
+C does not have the equivalent of \CC \lstinline[language={[GNU]C++}]{constexpr}, and it is currently beyond the scope of the \CFA project to implement a complex runtime interpreter in the transpiler.
+Nevertheless, the necessary language concepts exist to support this feature.
+
+
 \section{Enumeration Features}
+
+
 \section{Iteration and Range}
 
Index: doc/theses/jiada_liang_MMath/relatedwork.tex
===================================================================
--- doc/theses/jiada_liang_MMath/relatedwork.tex	(revision 38f5006ef2bee7ba7cdf8bc8ef954804e0243166)
+++ doc/theses/jiada_liang_MMath/relatedwork.tex	(revision 7bb516f9dde25f48bb6a37546feafba084354c29)
@@ -2,6 +2,6 @@
 \label{s:RelatedWork}
 
-Enumerations exist in many popular programming languages, \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.
-There are a large set of overlapping features among these languages, but each language has its own unique extensions and restrictions.
+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.
 
 
@@ -48,9 +48,10 @@
 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) of the type.
+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)
@@ -58,7 +59,13 @@
 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}
+
 Like C, Ada enumerators are unscoped, \ie enumerators declared inside of an enum are visible (projected) into the enclosing scope.
-Note, Ada is case-insensitive so names may appear in multiple forms and still be the same name (a questionable design decision).
-The only operators on enumeration types are the ordering operators, @=@, @<@, @<=@, @=@, @/=@, @>=@, @>@, where the ordering relation is given implicitly by the sequence of enumerators.
+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.
@@ -67,5 +74,5 @@
 \end{ada}
 Like \CFA, Ada uses an advanced type-resolution algorithm, including the left-hand side of assignment, to disambiguate among overloaded names.
-Figure~\VRef{f:AdaEnumeration} shows how ambiguities are handled using a cast, \eg @RGB'(Red)@.
+Figure~\VRef{f:AdaEnumeration} shows how ambiguities are handled using a cast, \eg \lstinline[language=ada]{RGB'(Red)}.
 
 \begin{figure}
@@ -73,16 +80,16 @@
 with Ada.Text_IO; use Ada.Text_IO;
 procedure test is
-   type RGB is ( Red, Green, Blue );
-   type Traffic_Light is ( Red, Yellow, Green );
-   procedure @Print@( Colour : RGB ) is begin
+   type RGB is ( @Red@, Green, Blue );
+   type Traffic_Light is ( @Red@, Yellow, Green );
+   procedure @Red@( Colour : RGB ) is begin
        Put_Line( "Colour is " & RGB'Image( Colour ) );
-   end Print;
-   procedure @Print@( TL : Traffic_Light ) is begin
+   end Red;
+   procedure @Red@( TL : Traffic_Light ) is begin
        Put_Line( "Light is " & Traffic_Light'Image( TL ) );
-   end Print;
+   end Red;
 begin
-    Print( Blue );				$\C[2in]{-- RGB}$
-    Print( Yellow );			$\C{-- Traffic\_Light}$
-    Print( @RGB'(Red)@ );		$\C{-- ambiguous without cast}\CRT$
+    @Red@( Blue );				 -- RGB
+    @Red@( Yellow );				-- Traffic_Light
+    @Red@( @RGB'(Red)@ );		-- ambiguous without cast
 end test;
 \end{ada}
@@ -91,11 +98,12 @@
 \end{figure}
 
-Like many other declarative items, enumeration literals can be renamed.
-In fact, such a literal is actually a function, so it has to be renamed as such:
-\begin{ada}
-function Red return P.RGB renames P.Red;
-\end{ada}
-Here, @RGB@ is assumed to be defined in package @P@, which is visible at the place of the renaming declaration.
-Renaming makes @Red@ directly visible without necessity to resort the use-clause.
+Ada provides an alias mechanism called \lstinline[language=ada]{renames} for aliasing types, especially to shorten package type names.
+\begin{ada}
+OtherRed : RGB renames Red;
+\end{ada}
+which suggests the \CFA extension to @typedef@.
+\begin{cfa}
+typedef RGB.Red OtherRed;
+\end{cfa}
 
 There are four enumeration pseudo functions (attributes): @'Pos@, @'Val@, @'Image@, and @'Value@.
@@ -105,5 +113,5 @@
 RGB'Val(0) = Red
 \end{ada}
-Funcion @Image@ returns enumerator label (in capital letters); the inverse function @Value@ returns the corresponding enumerator.
+Funcion @Image@ returns the enumerator label (in capital letters); the inverse function @Value@ returns the corresponding enumerator.
 \begin{ada}
 RGB'Image( Red ) = "RED"
@@ -111,10 +119,7 @@
 \end{ada}
 These attributes are important for simple IO (there are more elaborate IO facilities in @Ada.Text_IO@ for enumeration types).
-As well, an enumeration type, @T@, has the additional attributes, @T'First@, @T'Last@, @T'Range@, @T'Pred@, @T'Succ@, @T'Min@, and @T'Max@, producing an intuitively result based on the attribute name.
-
-
-Note that redeclaration as a function does not affect the staticness of the literal.
-
-\paragraph{Characters as enumeration literals} ~\newline
+As well, an enumeration type @T@ has the additional 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 leverages enumerations as the bases for character and boolean types.
 Rather unique to Ada is the use of character literals as enumeration literals:
 \begin{ada}
@@ -156,6 +161,12 @@
 Hence, the ordering of the enumerators is crucial to provide the necessary ranges.
 
-\paragraph{Using enumerations} ~\newline
-Enumeration types being scalar subtypes, type attributes such as @First@ and @Succ@ will allow stepping through a subsequence of the values.
+\begin{ada}
+type Subtype_Name is (Id1, Id2, Id3 ... );
+\end{ada}
+where @Id1@, @Id2@, etc. are identifiers or characters literals.
+In either case, the legal values of the type are referred to as "enumeration literals."
+Each of these values has a "position number" corresponding to its position in the list such that @Id1@ has position 0, @Id2@ has position 1, and the Nth value has position N-1.
+
+The enumeration attributes @First@ and @Succ@ allow stepping through a subsequence of the values.
 \begin{ada}
 case Day_Of_Week'First is
@@ -183,138 +194,4 @@
 \end{ada}
 
-\begin{ada}
-type Subtype_Name is (Id1, Id2, Id3 ... );
-\end{ada}
-where @Id1@, @Id2@, etc. are identifiers or characters literals.
-In either case, the legal values of the type are referred to as "enumeration literals."
-Each of these values has a "position number" corresponding to its position in the list such that @Id1@ has position 0, @Id2@ has position 1, and the Nth value has position N-1.
-
-
-\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
-}{}
-
-An enumeration type (or enum type) is a value type defined by a set of named constants of the underlying integral numeric type.
-To define an enumeration type, use the enum keyword and specify the names of enum members:
-\begin{csharp}
-enum Season {
-	Spring,
-	Summer,
-	Autumn,
-	Winter
-}
-\end{csharp}
-By default, the associated constant values of enum members are of type @int@;
-they start with zero and increase by one following the definition text order.
-
-You can explicitly specify any other integral numeric type as an underlying type of an enumeration type.
-You can also explicitly specify the associated constant values, as the following example shows:
-\begin{csharp}
-enum ErrorCode : ushort {
-	None = 0,
-	Unknown = 1,
-	ConnectionLost = 100,
-	OutlierReading = 200
-}
-\end{csharp}
-You cannot define a method inside the definition of an enumeration type.
-To add functionality to an enumeration type, create an extension method.
-
-The default value of an enumeration type @E@ is the value produced by expression @(E)0@, even if zero doesn't have the corresponding enum member.
-
-You use an enumeration type to represent a choice from a set of mutually exclusive values or a combination of choices.
-To represent a combination of choices, define an enumeration type as bit flags.
-
-\paragraph{Enumeration types as bit flags}
-
-If you want an enumeration type to represent a combination of choices, define enum members for those choices such that an individual choice is a bit field.
-That is, the associated values of those enum members should be the powers of two.
-Then, you can use the bitwise logical operators @|@ or @&@ to combine choices or intersect combinations of choices, respectively.
-To indicate that an enumeration type declares bit fields, apply the @Flags@ attribute to it.
-As the following example shows, you can also include some typical combinations in the definition of an enumeration type.
-\begin{csharp}
-[Flags]
-public enum Days {
-	None	  = 0b_0000_0000,  // 0
-	Monday	= 0b_0000_0001,  // 1
-	Tuesday   = 0b_0000_0010,  // 2
-	Wednesday = 0b_0000_0100,  // 4
-	Thursday  = 0b_0000_1000,  // 8
-	Friday	= 0b_0001_0000,  // 16
-	Saturday  = 0b_0010_0000,  // 32
-	Sunday	= 0b_0100_0000,  // 64
-	Weekend   = Saturday | Sunday
-}
-
-public class FlagsEnumExample {
-	public static void Main() {
-		Days meetingDays = Days.Monday | Days.Wednesday | Days.Friday;
-		Console.WriteLine(meetingDays);
-		// Output:
-		// Monday, Wednesday, Friday
-
-		Days workingFromHomeDays = Days.Thursday | Days.Friday;
-		Console.WriteLine($\$$"Join a meeting by phone on {meetingDays & workingFromHomeDays}");
-		// Output:
-		// Join a meeting by phone on Friday
-
-		bool isMeetingOnTuesday = (meetingDays & Days.Tuesday) == Days.Tuesday;
-		Console.WriteLine($\$$"Is there a meeting on Tuesday: {isMeetingOnTuesday}");
-		// Output:
-		// Is there a meeting on Tuesday: False
-
-		var a = (Days)37;
-		Console.WriteLine(a);
-		// Output:
-		// Monday, Wednesday, Saturday
-	}
-}
-\end{csharp}
-For more information and examples, see the System.FlagsAttribute API reference page and the Non-exclusive members and the Flags attribute section of the System.Enum API reference page.
-
-\paragraph{The System.Enum type and enum constraint}
-
-The System.Enum type is the abstract base class of all enumeration types.
-It provides a number of methods to get information about an enumeration type and its values.
-For more information and examples, see the System.Enum API reference page.
-
-You can use System.Enum in a base class constraint (that is known as the enum constraint) to specify that a type parameter is an enumeration type.
-Any enumeration type also satisfies the struct constraint, which is used to specify that a type parameter is a non-nullable value type.
-Conversions
-
-For any enumeration type, there exist explicit conversions between the enumeration type and its underlying integral type.
-If you cast an enum value to its underlying type, the result is the associated integral value of an enum member.
-\begin{csharp}
-public enum Season
-{
-	Spring,
-	Summer,
-	Autumn,
-	Winter
-}
-
-public class EnumConversionExample
-{
-	public static void Main()
-	{
-		Season a = Season.Autumn;
-		Console.WriteLine($\$$"Integral value of {a} is {(int)a}");  // output: Integral value of Autumn is 2
-
-		var b = (Season)1;
-		Console.WriteLine(b);  // output: Summer
-
-		var c = (Season)4;
-		Console.WriteLine(c);  // output: 4
-	}
-}
-\end{csharp}
-
 
 \section{\CC}
@@ -330,5 +207,5 @@
 }{}
 
-\CC is backwards compatible with C, so it inherited C's enumerations.
+\CC is largely backwards compatible with C, so it inherited C's enumerations.
 However, the following non-backwards compatible changes have been made.
 
@@ -398,4 +275,60 @@
 
 
+\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 intialization, 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}
 
@@ -409,17 +342,17 @@
 }{}
 
-The Golang enumeration is similar to classical Pascal \lstinline[language=pascal]{const}, where the type of a \lstinline[language=Golang]{const} name is the type of its constant.
+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 (left) enumerator value.
-\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 ( H = 0; Jack = "Jack"; J, K = 3; I )	$\C{// type change, implicit/explicit: 0 Jack Jack 3 3}$
-\end{Go}
+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.
+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}$
@@ -441,7 +374,365 @@
 	 @Thursday = 10;@ Friday = @iota - Wednesday + Thursday - 1@; Saturday; Sunday ) // 10, 11, 12, 13
 \end{Go}
-Note, \lstinline[language=Go]{iota} is advanced for the explicitly initialized enumerator, like the underscore @_@ identifier.
+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<PizzaStatus> 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<Pizza> getAllUndeliveredPizzas(List<Pizza> 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<Pizza> 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<Pizza> 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<Pizza.PizzaStatus, Pizza> map;
+\end{Java}
+Let's look at an example of how we can use it in practice:
+\begin{Java}
+public static EnumMap<PizzaStatus, List<Pizza>> 
+  groupPizzaByStatus(List<Pizza> pizzaList) {
+    EnumMap<PizzaStatus, List<Pizza>> pzByStatus = 
+      new EnumMap<PizzaStatus, List<Pizza>>(PizzaStatus.class);
+    
+    for (Pizza pz : pizzaList) {
+        PizzaStatus status = pz.getStatus();
+        if (pzByStatus.containsKey(status)) {
+            pzByStatus.get(status).add(pz);
+        } else {
+            List<Pizza> newPzList = new ArrayList<Pizza>();
+            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<Pizza> 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<Pizza.PizzaStatus,List<Pizza>> 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<Pizza> getAllUndeliveredPizzas(List<Pizza> input) {
+    return input.stream().filter(
+      (s) -> !deliveredPizzaStatuses.contains(s.getStatus()))
+        .collect(Collectors.toList());
+}
+
+public static EnumMap<PizzaStatus, List<Pizza>> 
+  groupPizzaByStatus(List<Pizza> pzList) {
+    EnumMap<PizzaStatus, List<Pizza>> map = pzList.stream().collect(
+      Collectors.groupingBy(Pizza::getStatus,
+      () -> new EnumMap<>(PizzaStatus.class), Collectors.toList()));
+    return map;
+}
+\end{Java}
+
 
 \section{Modula-3}
Index: doc/theses/jiada_liang_MMath/uw-ethesis.tex
===================================================================
--- doc/theses/jiada_liang_MMath/uw-ethesis.tex	(revision 38f5006ef2bee7ba7cdf8bc8ef954804e0243166)
+++ doc/theses/jiada_liang_MMath/uw-ethesis.tex	(revision 7bb516f9dde25f48bb6a37546feafba084354c29)
@@ -93,4 +93,5 @@
 %\usepackage{common}
 \CFAStyle						% CFA code-style
+\lstset{language=cfa,belowskip=-1pt}					% set default language to CFA
 
 \newcommand{\newtermFont}{\emph}
