The standard deriving mechanism in Haskell is quite useful but limited, which is why GHC has introduced several language extensions to make deriving more powerful and useful in more circumstances. In this section, you’ll learn about a few of them that have the largest impact on the way you approach writing code. Throughout this book, you’ll learn about others that are useful but less drastic in how they shape the way you approach writing your programs.
Deriving in Newtypes with Generalized Newtype Deriving
One of the first limitations that you’ll run into with deriving in type classes is the problem of having a limited number of type classes that you’re allowed to derive instances for. It makes sense that you might not be able to derive an instance of any given type class for a new data type, but for newtypes the limitation often means that you start writing very redundant code. As an example, imagine that you were writing a program that needed to work with currency. In order to make use of the type system to ensure that you are only ever adding compatible forms of currency, you might define a newtype wrapper to represent some unit of currency. For example, we’ll define the USD type as representing 0.001 USD:
| | newtype USD = USD { getMillis :: Integer } deriving ( Eq , Ord , Show ) |
Of course, you’d like to be able to add and subtract units of currency without having to unwrap the newtype for every operation, so it would be convenient to be able to use all the normal math functions that we could use with an Integer . Let’s add instances for Num , Real , Enum , and Integral .
| | instance Num USD where |
| | ( USD a) + ( USD b) = USD (a + b) |
| | ( USD a) * ( USD b) = USD (a * b) |
| | abs ( USD a) = USD (abs a) |
| | signum ( USD a) = USD (signum a) |
| | fromInteger = USD |
| | negate ( USD a) = USD (negate a) |
| | |
| | instance Real USD where |
| | toRational ( USD a) = toRational a |
| | |
| | instance Enum USD where |
| | toEnum a = USD (toEnum a) |
| | fromEnum ( USD a) = fromEnum a |
| | |
| | instance Integral USD where |
| | quotRem ( USD a) ( USD b) = |
| | let (a',b') = quotRem a b |
| | in ( USD a', USD b') |
| | toInteger ( USD a) = a |
As you look through all of these type class instances, you’ll notice that we’re not adding any additional logic here; in every case, we’re simply deferring to the type class instance of the type we’re wrapping.
Thankfully, the GeneralizedNewtypeDeriving extension allows us to automate away this boilerplate. This language extension allows newtype wrappers to derive any type class instances that are implemented by the type they are wrapping, and it does so by mechanically applying the same algorithm we’ve just used: unwrap the type, apply the type class function, and rewrap the result.
Let’s enable our language extension and look at the result:
| | {-# LANGUAGE GeneralizedNewtypeDeriving #-} |
| | |
| | newtype USD = USD { getMillis :: Integer } |
| | deriving ( Eq , Ord , Show , Enum , Num , Real , Integral ) |
Much better! Generalized newtype deriving makes using newtype wrappers much more convenient because you are no longer required to implement type classes manually if you’re only interested in using the underlying type’s instance.
| GeneralizedNewtypeDeriving |
|---|
|
| The GeneralizedNewtypeDeriving extension has been available since GHC 6.8.1. It’s enabled by default in GHC2021 but you’ll need to enable it manually if you are using Haskell2010 . This is a generally safe extension that shouldn’t interfere with any existing code. |
Deriving Via a Compatible Type
The last extension to deriving that you’ll learn about in this chapter turns some of what you’ve learned about type classes on its head. You’ve learned about how to use newtypes to add a new distinct type class instance to a type, but thanks to GHCs DerivingVia extension, you can also use newtypes as a template for how to define a type class for other types. This allows you to reduce boilerplate in your code by writing a derivation once and then re-using it in several different ways.
| DerivingVia |
|---|
|
| The DerivingVia extension has been available since GHC 8.6.1. It’s not enabled by default in either GHC2021 or Haskell2010 so you’ll need to enable it manually. This is generally a safe extension that shouldn’t interfere with any existing code. |
To see an example of how this works in action, we’ll return to a couple of our old friends, in particular Monoid and Maybe .
In base , Maybe has an instance of Monoid that allows you to combine the underlying values of the Maybe . For example, if you have some values with the type Maybe [Int] you can combine them with (<>) :
| | λ ( Just [1]) <> ( Just [2]) <> Nothing <> ( Just [3]) |
| | Just [1,2,3] |
This default monoid instance is quite useful, since it makes it very easy for us to combine optional values, but it’s not the only instance that we might want to use. One common pattern when working with Maybe values is selecting the first non-empty value from a set of values. As an example, consider an application that will select the first of several possible contact methods that’s available:
| | selectContact :: |
| | Maybe String -> Maybe String -> Maybe String -> Maybe String |
| | selectContact email sms phone = |
| | case email of |
| | Just email' -> Just email' |
| | Nothing -> |
| | case sms of |
| | Just sms' -> Just sms' |
| | Nothing -> phone |
It would be quite convenient if we could have a version of Maybe that offered a Monoid instance that made this easier. Since we can’t add a new instance to an existing type, we’ll use a type class called MyMaybe for which we can add the instance:
| | newtype MyMaybe a = MyMaybe ( Maybe a) deriving Show |
| | |
| | instance Semigroup ( MyMaybe a) where |
| | ( MyMaybe Nothing ) <> b = b |
| | a <> _ = a |
| | |
| | instance Monoid ( MyMaybe a) where |
| | mempty = MyMaybe Nothing |
If the implementation of Semigroup and Monoid looks familiar to you, it’s because it’s very similar to the instance of our Select type class that we defined for Maybe :
| | instance Select Maybe where |
| | empty = Nothing |
| | pick Nothing a = a |
| | pick a _ = a |
In order to reduce code duplication, let’s rewrite our Semigroup and Monoid instances to take advantage of the Select instance that we’ve already defined for Maybe :
| | instance Semigroup ( MyMaybe a) where |
| | ( MyMaybe a) <> ( MyMaybe b) = MyMaybe (pick a b) |
| | |
| | instance Monoid ( MyMaybe a) where |
| | mempty = MyMaybe empty |
This looks a lot nicer than our previous version that contained a lot of duplicated code, but something here still isn’t quite right. The first thing you might realize is nothing here is actually specific to either our MyMaybe newtype or to Maybe itself. We can actually define a valid Semigroup and Monoid instance for any Select instance. Along the same lines, these handwritten instances aren’t actually adding any value. They’re simply unwrapping and rewrapping a newtype and using the underlying Select instance we’ve already defined for Maybe .
To deal with this kind of duplication, GHC offers a new type of deriving strategy called deriving via , which you can enable with the DerivingVia language extension. Deriving via is a little bit like the mirror version of the newtype wrappers that you’ve already written. So far, you’ve used newtype wrappers in a “one to many” kind of way, where for some given underlying type you can define many different newtype wrappers that each have their own different instances of some type classes. With deriving via you can instead use a “many to one” strategy for deriving. To use deriving via you’ll need to create a type with one or more instances that will act like a template. Once you have your base type and instances defined, you can use deriving via to re-use the instance definitions for other types.
Let’s look at an example of how this works in practice.
We’ll start by creating a newtype wrapper that we’ll use to define the template for how we’d like to derive Semigroup and Monoid instances from a Select instance. We’ll call our newtype wrapper Sel because its job is basically wrapping Select . The wrapper itself is going to be very straightforward:
| | newtype Sel (f :: Type -> Type ) (a :: Type ) = Sel (f a) |
In plain English, Sel is parameterized by two types, and it wraps the type given by applying its second type parameter to the first.
It’s worth remembering here that when we defined our Select type class it was over a type with the kind Type -> Type :
| | class Select (f :: Type -> Type ) where |
Similarly, the first argument of Sel is a parameter with the kind f :: Type -> Type .
Next, let’s create instances of Semigroup and Monoid for our Sel type. We’re going to use the underlying Select instance, so we’ll add a type class constraint to our first type parameter, f :
| | instance ( Select f) => Semigroup ( Sel f a) where |
| | ( Sel a) <> ( Sel b) = Sel (pick a b) |
| | |
| | instance ( Select f) => Monoid ( Sel f a) where |
| | mempty = Sel empty |
So now, for any type with the kind Type -> Type and a Select instance, we have a monoid instance. Before we move on, let’s look at this in practice from ghci . We haven’t derived a Show instance for Sel in our example code, so for debugging purposes we’ll first make use of StandaloneDeriving to make it easier for us to see the values while we’re testing things out:
| | λ :set - XStandaloneDeriving |
| | λ deriving instance ( Show (f a)) => Show ( Sel f a) |
| | λ a = Sel ( Just 1) |
| | λ b = Sel ( Nothing ) |
| | λ a <> b |
| | Sel ( Just 1) |
| | λ b <> a |
| | Sel ( Just 1) |
| | λ ( Sel [1,2]) <> ( Sel [3,4,5]) |
| | Sel [1,2,3,4,5] |
Before we move on, let’s take a moment to look at the definitions of Sel and MyMaybe side by side:
| | newtype Sel (f :: Type -> Type ) (a :: Type ) = Sel (f a) |
| | newtype MyMaybe a = MyMaybe ( Maybe a) deriving Show |
| Roles |
|---|
|
| Roles describe different ways that two types can be equal. GHC supports three different kinds of equality. Notional equality requires that two types are exactly the same. Representational equality requires that they have the same runtime representation. Finally, Phantom equality allows any two types to be considered equal. It’s rare that you’ll need to think too much about type roles, and we won’t cover them in more detail in this book. You can refer to the GHC users guide for more information if you find that you need to deal with the role system directly. |
When you first learned about newtype , you learned that they offered a zero-overhead abstraction, and that the compiler guarantees that the newtype will store its value in the same way as the underlying type that it’s wrapping. In GHC, two types that have the same underlying runtime representation are considered representationally equal . When two types are representationally equal, the compiler can figure out how to safely coerce values from one type to the other.
In our example, both Sel Maybe a and MyMaybe a are representationally equal to Maybe a , which means that the compiler knows how to convert back and forth between Sel Maybe a and MyMaybe a . We can use this to our advantage to avoid writing boilerplate type class instances, because deriving via allows us to derive a type class instance for one type using the instance defined for another type that is representationally equal. Let’s look at it in action:
| | {-# LANGUAGE DerivingVia #-} |
| | |
| | newtype MyMaybe a = MyMaybe ( Maybe a) |
| | deriving Show |
| | deriving ( Semigroup , Monoid ) via ( Sel Maybe a) |
You’ll notice that we needed to add a new extension at the start of our file. The DerivingVia extension is necessary for us to use the deriving via strategy. With this new deriving via statement, we’re telling the compiler to use Sel as a template for how to derive the instances for Semigroup and Monoid . To do that, it will create an instance that converts our MyMaybe value into Sel Maybe , then calls the appropriate type class function, and converts the result back to a MyMaybe value.
Let’s look at our new type in action:
| | λ ( MyMaybe $ Just [1,2,3]) <> ( MyMaybe $ Just [3,4,5]) |
| | MyMaybe ( Just [1,2,3]) |
| | λ ( MyMaybe Nothing ) <> ( MyMaybe $ Just [3,4,5]) |
| | MyMaybe ( Just [3,4,5]) |
You’re not limited to using deriving via with types that already have an instance of the type class. For example, there’s no default Semigroup or Monoid instances for integral types, but we can use deriving via to borrow the instances defined by the Sum and Product types from Data.Semigroup :
| | {-# LANGUAGE DerivingVia #-} |
| | module MyNumericMonoids where |
| | import Data.Semigroup |
| | |
| | newtype MySum = MySum { getMySum :: Int } |
| | deriving ( Eq , Show ) |
| | deriving ( Semigroup , Monoid ) via ( Sum Int ) |
| | |
| | newtype MyProduct a = MyProduct { getMyProduct :: a } |
| | deriving ( Eq , Show ) |
| | deriving ( Semigroup , Monoid ) via ( Product a) |
| | λ :l MyNumericMonoids .hs |
| | λ mconcat $ map MySum [1..10] |
| | MySum {getMySum = 55} |
| | λ mconcat $ map Product [1..10] |
| | Product {getProduct = 3628800} |
Anyclass Deriving
Earlier in this chapter, you saw some examples of type classes that provided default definitions for all of their functions. For example, our Redacted type class could provide a default definition of its only function so long as we also provided a Show instance. Even though we could create instances of those type classes without providing an implementation for any of their functions, we still needed to explicitly add an instance. This can start to get inconvenient, especially when you have a large number of types that you need to write empty instances for.
| DeriveAnyClass |
|---|
|
| The DeriveAnyClass extension has been available since GHC 7.10.1. It’s not enabled in either GHC2021 or Haskell2010 so you’ll need to enable it manually. This is generally a safe extension, although it’s best enabled alongside the DerivingStrategies extension to avoid ambiguity about what strategy is being used to drive instances. |
The DeriveAnyClass language extension can help. When we enable this extension, we can derive any classes that we want, and GHC will add an empty instance declaration for us. Let’s take another look at our Redacted example from earlier in this chapter to see how we can use DeriveAnyClass to make our code a little shorter and nicer to read.
We’ll start by adding our new language extension:
| | {-# LANGUAGE DefaultSignatures #-} |
| | {-# LANGUAGE DeriveAnyClass #-} |
| | module AnyclassDemo where |
| | class Redacted a where |
| | redacted :: a -> String |
| | default redacted :: Show a => a -> String |
| | redacted = show |
Next, let’s define UserName . Now that we know about deriving we can skip the instance of Show and derive it. We’ll also make use of DeriveAnyClass to let us derive an instance of Redacted :
| | {-# LANGUAGE DefaultSignatures #-} |
| | {-# LANGUAGE DeriveAnyClass #-} |
| | module AnyclassDemo where |
| | |
| | class Redacted a where |
| | redacted :: a -> String |
| | default redacted :: Show a => a -> String |
| | redacted = show |
| | |
| | newtype UserName = UserName String deriving ( Show , Redacted ) |
Let’s load this up into ghci . If you are using a newer version of GHC, you may get a warning about using DerivingStrategies . If you see this warning, you can ignore it for now. We’ll cover this extension and when to use it in the next section.
| | λ UserName "george" |
| | UserName "george" |
| | λ redacted $ UserName "george" |
| | "UserName \"george\"" |
Using a derived instance of Show has changed our output slightly from the earlier examples, but overall we can see that our new version of the code is working exactly as we’d hoped, and with substantially less code.
Next, let’s see what happens if we try to use our new extension to derive an instance of Redacted for our Password type, while still avoiding creating a Show instance:
| | newtype Password = Password String deriving ( Redacted ) |
If we try to load this into ghci you’ll see that once again we get an error because we’ve failed to provide either a Show instance or a definition of redacted :
| | λ :load AnyclassDemo |
| | AnyclassDemo.hs:11:46: error: |
| | • No instance for (Show Password) |
| | arising from the 'deriving' clause of a data type declaration |
| | Possible fix: |
| | use a standalone 'deriving instance' declaration, |
| | so you can specify the instance context yourself |
| | |
| | |
| | • When deriving the instance for (Redacted Password) |
| | | |
| | 11 | newtype Password = Password String deriving (Redacted) |
| | | ^^^^^^^^ |
| | Failed, no modules loaded. |
Deriving Strategies
The ability to derive an empty instance for any class is useful, but as you may have seen in the last section, if you are using a newer version of GHC, this extension can sometimes be a source of confusion. The problem is the interaction between GeneralizedNewtypeDeriving and DeriveAnyClass can be unexpected. To see an example of why, let’s imagine that we’re going to add another user type, called an AdminUser , that is a newtype wrapper around our existing UserName . We’ll also change our Redacted instance for UserName to add some extra formatting. Finally, we’ll turn on GeneralizedNewtypeDeriving since we may want to use it as we’re developing our program:
| | {-# LANGUAGE DefaultSignatures #-} |
| | {-# LANGUAGE DeriveAnyClass #-} |
| | {-# LANGUAGE GeneralizedNewtypeDeriving #-} |
| | module AnyclassDemo where |
| | |
| | class Redacted a where |
| | redacted :: a -> String |
| | default redacted :: Show a => a -> String |
| | redacted = show |
| | |
| | newtype UserName = UserName String deriving Show |
| | instance Redacted UserName where |
| | redacted ( UserName user) = "UserName: " <> user |
| | |
| | newtype AdminUser = Adminuser UserName deriving ( Show , Redacted ) |
Now, let’s load this program up into ghci and look at some redacted values to see what we get. We’ll start by looking at a redacted user:
| | λ redacted $ UserName "george" |
| | "UserName: george" |
As we’d expect, we’re using our new Redacted instance to get some nicer formatting when we show off our username. What if we create an admin user? It turns out that there are two possibilities. If GHC uses GeneralizedNewtypeDeriving , then it will use the instance that we’ve provided in UserName to generate an instance for AdminUser . On the other hand, if we use the approach enabled by DeriveAnyClass , we’ll get the instance provided to use based on our Show instance, and get the somewhat less readable formatting. Let’s try it out in ghci :
| | λ redacted $ Adminuser ( UserName "george" ) |
| | "Adminuser (UserName \" george \" )" |
As you can see, in this case we’re using the default definition of redacted that we get from an empty instance when we use the DeriveAnyClass approach. It turns out that, whenever it’s presented with the option between generalized newtype deriving and anyclass deriving, GHC will pick the anyclass approach to deriving instances. Knowing the rule lets us avoid surprises, but it would be helpful if we could choose which approach we want it to take when generating instances.
| DerivingStrategies |
|---|
|
| The DerivingStrategies extension has been available since GHC 8.2.1. It’s not enabled by default in either GHC2021 or Haskell2010 so you’ll need to enable it manually. This is a safe extension that shouldn’t interfere with any existing code. |
We can choose the strategy GHC takes by enabling the DerivingStrategies extension. With this extension, we can specifically tell the compiler how we want it to try to generate our type class instances. Let’s turn it on and use it for AdminUser , and then we’ll look a bit more closely at how it works:
| | {-# LANGUAGE GeneralizedNewtypeDeriving #-} |
| | {-# LANGUAGE DefaultSignatures #-} |
| | {-# LANGUAGE DeriveAnyClass #-} |
| | {-# LANGUAGE DerivingStrategies #-} |
| | module AnyclassDemo where |
| | |
| | class Redacted a where |
| | redacted :: a -> String |
| | default redacted :: Show a => a -> String |
| | redacted = show |
| | |
| | newtype UserName = UserName String deriving Show |
| | instance Redacted UserName where |
| | redacted ( UserName user) = "UserName: " <> user |
| | |
| | newtype AdminUser = Adminuser UserName |
| | deriving stock Show |
| | deriving newtype Redacted |
In this example, we now have two different deriving clauses associated with our single AdminUser type. We’ve also added two new keywords, stock and newtype .
With the DerivingStrategies extension we can add several deriving clauses when we define a type, and each of those can have an associated deriving strategy. There are four strategies that you can use:
-
stock can be used if you are trying to derive one of the standard derivable type classes and want to use the standard approach defined in the Haskell standard.
-
newtype tells the compiler to use the generalized newtype deriving strategy to create an instance based on a newtype wrapper.
-
anyclass tells the compiler to generate an empty instance declaration, which is the default when DeriveAnyClass is enabled.
-
via uses the deriving via strategy that you learned about earlier in this chapter.
In newer versions of GHC, the GeneralizedNewtypeDeriving extension is enabled automatically, and the compiler now emits more warnings encouraging users to enable the DerivingStrategies extension and make use of explicit deriving strategies. In the rest of this book, we’ll typically omit deriving strategies to keep the examples compatible with older Haskell versions, but you are encouraged to start using deriving strategies in your own code, since this style is likely to become more popular in newer Haskell code.