One of the key limitations that you’ve seen when working with type classes is that each data type must have at most a single instance of the type class. Having more than one implementation of show or read for a type would not only make it impossible for the compiler to select an implementation to use, it would also make the program unmaintainably confusing as the intention behind what a type class means for any given type would be obscured. As with the MyResult type that you built in the last section, which was structurally identical to Either , it’s common that you might want to have some underlying data structure represented by more than one type, each with its own name and perhaps its own type class instances as well.
To address this problem, Haskell gives us another way of creating a type using the newtype keyword. Types created with newtype are often referred to as newtype wrappers because a newtype is simply a way of wrapping an existing type. Unlike data types, newtypes are “zero-cost” abstractions. The compiler guarantees that using a newtype will not introduce any additional computational or memory overhead, and the underlying data structure will share the same representation as the type that it wraps.
Creating a newtype looks very similar to creating a new data type, except that you’ll use the newtype keyword instead of data . Let’s create a new wrapper around Either to see an example:
| | newtype MyEither a b = MyEither ( Either a b) |
Although this looks very similar to a data declaration, newtypes are limited in ways data declarations are not. Newtypes must always have exactly one constructor, which itself must have exactly one field. You can’t use sum types or have multiple fields for a newtype. It’s typical for newtype wrappers to use record syntax to name their field. To make our example more idiomatic, we would say:
| | newtype MyEither a b = MyEither { getEither :: Either a b } |
In this example, MyEither takes two type parameters, which we pass on directly to the underlying type, but this isn’t an inherent restriction. Newtypes can take more or fewer type parameters. All of the following would also be valid newtype definitions for example:
| | newtype MyEither = MyEither { getEither :: Either String Int } |
| | newtype MyEither a = MyEither { getEither :: Either String a } |
| | newtype MyEither a = MyEither { getEither :: Either a a } |
| | newtype MyEither a b c = MyEither { getEither :: Either a b } |
Even though a newtype is just a wrapper around some other type at the lowest level, it is a “real” type. Unlike a type alias, you can’t directly substitute a newtype with the type that it’s wrapping. This can be very helpful if you want to maintain a clean logical separation between different types in your code, while still benefiting from having a single optimized underlying data structure. Newtypes also allow you to provide different type class instances for a single representation of a data structure. Type aliases, since they aren’t actually their own distinct types, don’t have their own type class instances. Finally, newtypes allow you to express certain things that aren’t otherwise directly allowed due to limitations in the type checker. In the rest of this section we’ll explore each of these use-cases for type classes.
Using Type Classes with Newtypes
One of the biggest reasons for using newtype wrappers is to provide type class instances for a type that you’re wrapping. There are two reasons that you might want to use a newtype to create type class instances rather than creating instances for the underlying type: to avoid orphan instances , and to support multiple different type class instances for an underlying type. In this section, we’ll look at a single example that demonstrates both of these reasons for using newtype wrappers.
An orphan instance is a type class instance that you define in a module where you didn’t define either the type class you’re creating an instance of, or the underlying type that you’re creating an instance for. In other words, it’s an “orphan instance” because the instance doesn’t “belong to” the implementation of the type class or the data type. Although orphan instances aren’t an error that will stop your program from building, they will generate a warning, and they are considered bad style and a risk to the long term maintainability of your application. The biggest risk with orphan instances is that in the future, the library that defined the type class, or the underlying type, might choose to add an instance. In Haskell there’s a rule that in your entire program there can only ever be one single instance of a type class for each type. That means it’s very easy for an update to a library to break your code if it started providing an instance of something that you’ve already defined an orphan instance for. Not only do you risk your program failing to compile because of conflicting instances, it also makes your code harder to maintain because you will have a non-standard implementation of the type class.
Even when you have defined your data type or the type class you want to create an instance of, it’s not uncommon to have more than one plausible way of creating an instance for a type class. Since you’re limited to a single instance per type, using newtype wrappers allows you to define multiple instances of a type class while still using a single underlying data definition and not introducing any unnecessary overhead.
Let’s turn our attention to a pair of type classes that you’ve been making use of already: Semigroup and Monoid . We can look at their definitions in ghci :
| | λ :info Semigroup |
| | class Semigroup a where |
| | (<>) :: a -> a -> a |
| | GHC . Base .sconcat :: GHC . Base . NonEmpty a -> a |
| | GHC . Base .stimes :: Integral b => b -> a -> a |
| | {-# MINIMAL (<>) #-} |
| | λ :info Monoid |
| | class Semigroup a => Monoid a where |
| | mempty :: a |
| | mappend :: a -> a -> a |
| | mconcat :: [a] -> a |
| | {-# MINIMAL mempty #-} |
You’ll recognize the (<>) operator from Semigroup , which is how you’ve been concatenating lists and strings throughout this book. The Monoid type class builds on Semigroup by adding mempty , which represents some initial starting or empty value. One good way of seeing what the behavior of values and functions defined by type classes should be is to look at them in ghci . As an example, let’s look at several different mempty values:
| | λ mempty @[ Int ] |
| | [] |
| | λ mempty @ String |
| | "" |
| | λ mempty @( Maybe [ Int ]) |
| | Nothing |
You can see that mempty returns some sort of zero or initial value. In fact, the contract for mempty says that it should always be true that (mempty <> a) == a . Later on in this book, you’ll learn more about laws for different kinds of type classes and how to think about them. For the moment, let’s return to the idea of a “zero” or “initial” value. It’s intuitive to realize that the “empty” value for a list is an empty list, and it’s not a huge leap to recognize that Nothing is a kind of starting point for a Maybe value. This is a bit misleading though, because we’re thinking about mempty as some value of a particular type. In reality, mempty is related to a particular operation . For numeric types like Int , we have more than one choice in how we might want to combine values, and each of those choices gives us a different mempty value. Let’s look at some concrete examples. First we’ll look at addition. Addition lets us combine two numbers by adding them together, so the “empty” starting point is 0, since anything added to 0 gives us back the original number. Next, multiplication is another way that we can merge two numbers into a single number, but the “empty” value for multiplication is 1. In other words, (<>) defines some operation for a type, and mempty is the identity for that operation.
As you can imagine, having two very clear choices for how we might define Semigroup and Monoid for a type like Int presents us with a bit of a problem. How do we pick which one to use? Thankfully, with newtype we can avoid the question and provide users with both options. To do that, we’ll need to start by adding a newtype for each operation we want to support:
| | newtype Product = Product { getProduct :: Int } |
| | newtype Sum = Sum { getSum :: Int } |
Next, we’ll need to create instances of Semigroup and Monoid for each newtype . This example will show you how to do this for Product . As an exercise, define the instances for Sum on your own:
| | instance Semigroup Product where |
| | ( Product a) <> ( Product b) = Product (a * b) |
| | |
| | instance Monoid Product where |
| | mempty = Product 1 |