Chapter 5.  Algebraic Data Types

In this chapter, I turn to the F# features that are (almost) missing among mainstream programming languages, such as C#, that are collectively referred to in computer science as algebraic data types (https://en.wikipedia.org/wiki/Algebraic_data_type). They advance primitive data types to the higher type level with the help of the composition of other types (primitive or in-turn composite) which are as follows:

  • Tuples and records that represent product algebraic data types
  • Discriminated unions that represent sum algebraic types

I'll cover the same facets for each of these composite types as follows:

  • Type composition
  • Type equality and comparison
  • Type decomposition
  • Type augmentation

I will revisit the pattern matching as a type decomposition facility that can often be applied outside of the match construction.

Combining data with algebraic data types

Usually a conventional programmer considers the matter of data composition through the prism of the object-oriented paradigm.

Everyone usually intuitively understands that primitive data types are basic, built-in types supported by a compiler or library: int64, string, bigint (although if viewed with a rigor, string may be considered as char array, and bigint as a record).

The next thing programmers learn is that instances of primitive types can be aggregated into collections such as arrays or lists. However, these collections are monomorphic. That is, the type of all collection members must be the same. Pretty limiting, huh?

The object-oriented paradigm extends primitive types with classes. The class just represents a custom type that hides the details of the data composition with the help of encapsulation and offers visibility to just the public properties. Typically, .NET libraries offer plenty of such composite types, for example, System.DateTime.

F# certainly supports this way of constructing composite data types as well. However, following the cumbersome and error-prone venue of Plain  Old  Objects (POCO) each time when a composite type is required is not in line with the F# promise of succinct and error-free code. What would be the way out? Welcome to algebraic data types!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset