Records are a useful feature of Haskell’s type system, and you’ll use them regularly in the code you write, but they are just a small part of the power of types in Haskell. In this section, you’ll learn about several other useful features of Haskell’s type system, which broadly fall under the term algebraic datatypes , or ADTs .

The name algebraic datatype comes from the formal study of types and type systems. We won’t get into the details of the name or the underlying theory in this book, but we’ll continue to use the term, along with some related terms like sum type and product type when we’re referring to particular types of features. These are commonly used terms when working with Haskell, but you can learn what they mean and how to use them in the context of writing Haskell programs without needing to understand the theory that gave them their names.

Using Sum Types as Enums

Earlier in this chapter, you learned about product types and records. Product types let you combine many other types together. Another way you can use types to help you better structure data is to use them to represent a choice between two types. We call these types sum types . Let’s work through a simple example by looking at an implementation of Bool , which is one of the simplest sum types that we can define.

​  ​ data ​ ​ Bool ​ = ​ True ​ | ​ False ​

In this example, we’ve defined a new type, Bool , which has two value constructors, True and False . Neither of these value constructors take any parameters, so they each have a single inhabitant.

A Bool can be either True or False , and so the type has two inhabitants.

Of course, we can extend this beyond a choice between two options. Haskell programs frequently use sum types to enumerate all of the inhabitants of a specific type. For example, if we wanted to create a type to represent the cardinal directions, we can easily list out all of them as a sum type:

​  ​ data ​ ​ Direction ​ = ​ North ​ | ​ South ​ | ​ East ​ | ​ West ​

Creating Sum Types with Data

In many cases, we don’t want to choose between product or sum types. Consider the problem of storing some contact information for a user who might want to provide a phone number for receiving text messages or, alternatively, a mailing address for receiving written correspondence. As with the examples of sum types you’ve already looked at, we have a clear choice between two different value constructors, which in this case we can call TextMessage and Mail . However, each of these value constructors need to take some parameters: a phone number for text messages, or a mailing address for sending mail. The syntax for doing this follows naturally from the syntax of sum and product types. We create a value constructor for each branch as we’ve done for previous sum types, but for each of these value constructors we can add any number of parameters, just like we did for product types.

Let’s look at a concrete example:

​  ​ data ​ ​ PreferredContactMethod ​ = ​ Email ​ ​ String ​
​  | ​ TextMessage ​ ​ String ​
​  | ​ Mail ​ ​ String ​ ​ String ​ ​ String ​ ​ Int ​
​  
​  emailContact :: ​ PreferredContactMethod ​
​  emailContact = ​ Email ​ ​ "[email protected]" ​
​  
​  textContact :: ​ PreferredContactMethod ​
​  textContact = ​ TextMessage ​ ​ "+1 307 555 0100" ​
​  
​  mailContact :: ​ PreferredContactMethod ​
​  mailContact = ​ Mail ​ ​ "1123 S. Road St." ​ ​ "Suite 712" ​ ​ "Examplesville, OH" ​ 98142

This pattern of combining multiple product types into a single new type is sometimes referred to as a sum of products , although the pattern is so common that in practice most Haskell developers will casually just refer to sum, product, or sum-of-product types as “a type.”

Using Sum Types in Practice

Now that you’ve created some contact information, it would be useful to be able to do something with it. Let’s continue with the example by writing a function called confirmContact that will generate some confirmation text that we could display to a user, letting them know that we’ll use their preferred contact method for future communications.

Just like the data types you created in the previous section, you can use pattern matching to extract the values from your new type. When you were working with a single data constructor, you only needed to pattern match for it, and so it made sense to use a pattern to match values at the function argument level. When you are working with sum types you can still pattern match function arguments directly, but it’s more common to use a case statement. In this example, we’re using a case statement to both select the specific constructor as well as to extract its arguments.

​  confirmContact :: ​ PreferredContactMethod ​ -> ​ String ​
​  confirmContact contact =
​  ​ case ​ contact ​ of ​
​  ​ Email ​ emailAddress ->
​  ​ "Okay, I'll email you at " ​ <> emailAddress
​  ​ TextMessage ​ number ->
​  ​ "Okay, I'll text you at " ​ <> number
​  ​ Mail ​ street1 street2 citystate zip ->
​  ​ "Okay, I'll send a letter to ​​ \n ​​ " ​
​  <> street1 <> ​ " ​​ \n ​​ " ​
​  <> street2 <> ​ " ​​ \n ​​ " ​
​  <> citystate <> ​ " " ​ <> show zip

In some circumstances, you might not care about all of the fields when pattern matching in sum types. In that case, you can use a pair of empty brackets to represent the parameters to the data constructor without having to type them all out. Although this looks similar to the syntax for record wildcards, it doesn’t require any language extensions. Let’s look at an example. If you did not want to print out a user’s actual contact information for privacy reasons, you could write a variant of confirmContact that only looks at the constructor:

​  confirmContact' :: ​ PreferredContactMethod ​ -> ​ String ​
​  confirmContact' contact =
​  ​ case ​ contact ​ of ​
​  ​ Mail ​{} -> ​ "Okay, I'll send you a letter!" ​
​  ​ Email ​{} -> ​ "Okay, I'll email you!" ​
​  ​ TextMessage ​{} -> ​ "Okay, I'll text you!" ​

You might find yourself wondering what the benefit is of using a single sum type here rather than three different data types. You could, after all, write each branch of the case statement in our example as a function that takes some unique type and generates the right output:

​  ​ data ​ ​ Email ​ = ​ Email ​ ​ String ​
​  ​ data ​ ​ TextMessage ​ = ​ TextMessage ​ ​ String ​
​  ​ data ​ ​ Mail ​ = ​ Mail ​ ​ String ​ ​ String ​ ​ String ​ ​ Int ​
​  
​  emailContact :: ​ Email ​
​  emailContact = ​ Email ​ ​ "[email protected]" ​
​  
​  textContact :: ​ TextMessage ​
​  textContact = ​ TextMessage ​ ​ "+1 307 555 0100" ​
​  
​  mailContact :: ​ Mail ​
​  mailContact = ​ Mail ​ ​ "1123 S. Road St." ​ ​ "Suite 712" ​ ​ "Examplesville, OH" ​ 98142
​  
​  confirmEmailContact (​ Email ​ emailAddress) =
​  ​ "Okay, I'll email you at " ​ <> emailAddress
​  
​  confirmTextContact (​ TextMessage ​ number) =
​  ​ "Okay, I'll text you at " ​ <> number
​  
​  confirmMailContact (​ Mail ​ street1 street2 citystate zip) =
​  ​ "Okay, I' ll send a letter to ​​ \n ​​ " ​
​  <> street1 <> ​ " ​​ \n ​​ " ​
​  <> street2 <> ​ " ​​ \n ​​ " ​
​  <> citystate <> ​ " " ​ <> show zip

This second approach might look appealing, and seems to offer even better type safety, but now consider the problem of writing a function that returns a preferred contact method for several different users. Using distinct types for each contact method makes this difficult because the function would need to return a value with a different type depending on the preferred contact method. Using sum types, however, we can easily express this function since all of our different values are still of type PreferredContactMethod :

​  contactForUser :: ​ String ​ -> ​ PreferredContactMethod ​
​  contactForUser username =
​  ​ case ​ username ​ of ​
​  ​ "George" ​ ->
​  ​ Email ​ ​ "[email protected]" ​
​  ​ "Porter" ​ ->
​  ​ TextMessage ​ ​ "+1 307 555 0100" ​
​  ​ "Remmy" ​ ->
​  ​ Mail ​ ​ "1123 S. Road St." ​ ​ "Suite 712" ​ ​ "Examplesville, OH" ​ 98142
​  name ->
​  ​ Email ​ $ name <> ​ "@example.com" ​

Another example where sum types can help you get around restrictions you might face with multiple types is when dealing with lists. You know that you can only store a single type in a list, but if you have different types of values that you need to store, you can wrap them in a sum type.

Let’s look at one more example, using sum types to store a list of strings and numbers:

​  ​ data ​ ​ StringOrNumber ​ = ​ S ​ ​ String ​ | ​ N ​ ​ Int ​
​  
​  stringsAndNumbers :: [​ StringOrNumber ​]
​  stringsAndNumbers =
​  [ ​ S ​ ​ "This list has" ​
​  , ​ N ​ 2
​  , ​ S ​ ​ "different types of values" ​
​  ]

Summing Records

Just as you were able to use record syntax to provide field names and get field selectors for data types with a single constructor, you can also use record syntax for sum types. The syntax for this is a combination of the record syntax you’ve seen using curly braces and field names, and the sum type syntax using | . Let’s look at an example of combining sum types and records to create a sum type over customers and employees, along with a couple of example values:

​  ​ data ​ ​ Person ​ = ​ Customer ​
​  { name :: ​ String ​
​  , balance :: ​ Int ​
​  }
​  | ​ Employee ​
​  { name :: ​ String ​
​  , managerName :: ​ String ​
​  , salary :: ​ Int ​
​  }
​  
​  george =
​  ​ Customer ​ { name = ​ "Georgie Bird" ​
​  , balance = 100 }
​  
​  porter =
​  ​ Employee ​ { name = ​ "Porter P. Pupper" ​
​  , managerName = ​ "Remi" ​
​  , salary = 10 }

Using sum types with records gets you the same benefits as using records. As you saw in the example, you can use record syntax to make use of named fields when you construct a value. You can also use the field names to access values:

​  ​ λ ​ name george
​  ​ "Georgie Bird" ​
​  ​ λ ​ name porter
​  ​ "Porter P. Pupper" ​

Unfortunately, record syntax when combined with sum types introduces a source for potential errors. Record fields that exist only for certain data constructors are partial functions—if you try to access a field that doesn’t exist for the value you’ve constructed, you’ll get a runtime exception:

​  ​ λ ​ balance george
​  100
​  ​ λ ​ balance porter
​  *** ​ Exception ​: ​ No ​ match ​ in ​ record selector balance
​  ​ λ ​ managerName porter
​  ​ "Remi" ​
​  ​ λ ​ managerName george
​  ​ "*** Exception: No match in record selector managerName ​

The risk of runtime errors from these partial record selectors means that most Haskell developers generally avoid directly combining sum types and records. Instead of directly mixing records and sum types, we can create a new record for each constructor. This will prevent us from ever trying to access fields that don’t exist in a particular branch of our sum type. Let’s look at an example:

​  ​ data ​ ​ CustomerInfo ​ = ​ CustomerInfo ​
​  { customerName :: ​ String ​
​  , customerBalance :: ​ Int ​
​  }
​  
​  ​ data ​ ​ EmployeeInfo ​ = ​ EmployeeInfo ​
​  { employeeName :: ​ String ​
​  , employeeManagerName :: ​ String ​
​  , employeeSalary :: ​ Int ​
​  }
​  
​  ​ data ​ ​ Person ​
​  = ​ Customer ​ ​ CustomerInfo ​
​  | ​ Employee ​ ​ EmployeeInfo ​
​  
​  george = ​ Customer ​ $
​  ​ CustomerInfo ​ { customerName = ​ "Georgie Bird" ​
​  , customerBalance = 100 }
​  
​  porter = ​ Employee ​ $
​  ​ EmployeeInfo ​ { employeeName = ​ "Porter P. Pupper" ​
​  , employeeManagerName = ​ "Remi" ​
​  , employeeSalary = 10
​  }

In this example, we’ve added records to hold the particular values associated with customers and employees independently. This avoids problems with partial field selectors, but now getting at any of our data means that we need to pattern match on Person and then call the appropriate field selector.

One way that we can work around this is to add functions to our API to make it easier to get at data that exists for all of the different potential values in our sum type. For example, since both customers and employees have names, we can add a function getPersonName to get the name for any person:

​  getPersonName :: ​ Person ​ -> ​ String ​
​  getPersonName person =
​  ​ case ​ person ​ of ​
​  ​ Employee ​ employee -> employeeName employee
​  ​ Customer ​ customer -> customerName customer

What about functions to access fields that only exist in one constructor? Let’s take a look at the employeeManager field to start with. The employeeManager field is a String , and it only exists in EmployeeInfo , which we have when we’ve constructed a person using the Employee constructor.

​  getPersonManager :: ​ Person ​ -> ​ String ​
​  getPersonManager person =
​  ​ case ​ person ​ of ​
​  ​ Employee ​ employee -> employeeManagerName employee
​  ​ Customer ​ customer -> undefined

Now it seems like we’re back in the land of partial functions. As long as we get an employee passed in, we can get the manager, but as soon as we get a customer we’ll fail, because we’ll encounter an undefined value. What we need to do is return the name of a manager if the person is an employee, but if they are a customer we need some value that says “nothing to see here, move along.” That sounds a lot like a sum type! Let’s create a new type called MaybeString to capture this:

​  ​ data ​ ​ MaybeString ​ = ​ NoString ​ | ​ SomeString ​ ​ String ​

With the new type in hand, you can write a function that returns SomeString if there’s a valid value, or NoString if there isn’t:

​  getPersonManager :: ​ Person ​ -> ​ MaybeString ​
​  getPersonManager person =
​  ​ case ​ person ​ of ​
​  ​ Employee ​ employee -> ​ SomeString ​ (employeeManagerName employee)
​  ​ Customer ​ _customer -> ​ NoString ​

We can take the same approach with customerBalance and employeeSalary . You can imagine that we could create a new type named MaybeInt that works just like MaybeString , and use it to create functions to get a person’s balance and salary:

​  getPersonBalance, getPersonSalary :: ​ Person ​ -> ​ MaybeInt ​

As an exercise, implement the MaybeInt type and the getPersonBalance and getPersonSalary functions yourself. When you’re finished, you can move on to the next section where you’ll learn about another more general way to implement this pattern.

Creating Polymorphic Types

Having separate implementations for optional values of each type that we might return works, but it can quickly get out of hand. Not only do we have to create, and export, many new types, we also must write variations of many utility functions several times, require that our users learn about and remember the name of several types, and in general make a lot of extra work for ourselves. Thankfully we can avoid all of this additional work by making use of type parameters . Type parameters allow you to make a type constructor that takes some types as parameters. When you pass some parameters to a type constructor, you end up with a type. You have already worked with parameterized types when you’ve created lists and tuples, but until now we’ve glossed over the details.

Let’s start by looking at the definition of the Maybe type. This will already be defined for you when you start a new program, since it’s part of the Prelude . The Prelude is a module that’s imported by default in all Haskell programs, and it contains all of the things from the standard library that are available by default. If you want to write this yourself as you follow along, you can pick another name, like MyMaybe .

​  ​ data ​ ​ Maybe ​ a = ​ Nothing ​ | ​ Just ​ a

In this example, Maybe by itself isn’t a full type, so we call it a type constructor . When we pass a parameter to Maybe , we’ll end up with a type like Maybe Int or Maybe String . The type variable a is a type parameter . Just like with polymorphic functions, the type variable a here can represent any type, but it will always represent the same type everywhere in our type definition. In many cases, you’ll want to work with some specific instance of a type, like in the following examples where we implement balance , salary , and manager in terms of Maybe :

​  getPersonBalance :: ​ Person ​ -> ​ Maybe ​ ​ Int ​
​  getPersonBalance person =
​  ​ case ​ person ​ of ​
​  ​ Customer ​ customerInfo ->
​  ​ Just ​ $ customerBalance customerInfo
​  ​ _ ​ ->
​  ​ Nothing ​
​  
​  getPersonSalary :: ​ Person ​ -> ​ Maybe ​ ​ Int ​
​  getPersonSalary person =
​  ​ case ​ person ​ of ​
​  ​ Employee ​ employeeInfo ->
​  ​ Just ​ $ employeeSalary employeeInfo
​  ​ _ ​ ->
​  ​ Nothing ​
​  
​  getPersonManager :: ​ Person ​ -> ​ Maybe ​ ​ String ​
​  getPersonManager person =
​  ​ case ​ person ​ of ​
​  ​ Employee ​ employeeInfo ->
​  ​ Just ​ $ employeeManagerName employeeInfo
​  ​ _ ​ ->
​  ​ Nothing ​

In other cases, however, you may want to work with polymorphic versions of parameterized types. In this case, you can use a type variable just like you would with any other polymorphic function. For example, we can write a function that will take any type of Maybe value and convert it to a list of the appropriate type:

​  maybeToList :: ​ Maybe ​ a -> [a]
​  maybeToList (​ Just ​ val) = [val]
​  maybeToList ​ Nothing ​ = ​ [] ​

The Maybe type generalizes a single optional value. It’s frequently used both to signal optional inputs to a function as well as to make partial functions safe by indicating that there might not be a valid output for some input. Although useful, sometimes we want a slightly richer choice between two types, especially when we might want to represent success or detailed failure, or a choice between two paths. In this case, you can use another common type defined in Prelude , the Either type. Either takes two type parameters, representing the types of a left and right value. By convention in Haskell applications, Left typically represents an error case, and Right represents a success case.

​  ​ data ​ ​ Either ​ a b = ​ Left ​ a | ​ Right ​ b

Let’s look at a couple of examples. We’ll start by writing a function that tries to get the Right value of an Either :

​  eitherToMaybe :: ​ Either ​ b a -> ​ Maybe ​ a
​  eitherToMaybe e =
​  ​ case ​ e ​ of ​
​  ​ Left ​ ​ _ ​ -> ​ Nothing ​
​  ​ Right ​ val -> ​ Just ​ val

In some cases, you might want to pass a parameterized type as an argument to another parameterized type. In that case, you need to use parentheses to group the types. Let’s look at a concrete example by writing a function that takes an Either value to its Right constructor.

​  handleMissingRight :: ​ Either ​ ​ String ​ (​ Maybe ​ a) -> ​ Either ​ ​ String ​ a
​  handleMissingRight e =
​  ​ case ​ e ​ of ​
​  ​ Left ​ err -> ​ Left ​ err
​  ​ Right ​ (​ Just ​ val) -> ​ Right ​ val
​  ​ Right ​ ​ Nothing ​ -> ​ Left ​ ​ "Missing value" ​

Of course you can keep adding parameters as you need. Most of the time one or two parameters are enough, but you’ll occasionally see types with three, four, or even five parameters in some common Haskell libraries.