Now that we’ve had a chance to see several different examples of how we can use monad transformers, let’s try to put it together into a more useful example. In this section, we’ll build a utility that will let us create archives of files. Along the way, we’ll look for some opportunities to refine our approach to our monad transformer definitions to improve their ergonomics.
Our application allows users to define a file archive using a small language that we’ll parse. The language will let our users create a new archive, add items to the archive by importing files from disk, and add items by defining them inline. Here’s an example of an archive with three files:
| | archive "example.archive": |
| | |
| | import "./example1.txt" |
| | |
| | new-file "inline-example.txt": |
| | this is some text |
| | it can have newlines |
| | but it needs to be indented |
| | |
| | import "./example2.txt" |
Two of the archive files, example1.txt and example2.txt , are imported the local filesystem. The third file, inline-example.txt , is defined inline.
Creating an Archiver
We’ll start building our archiver by defining a new module. We’ll continue using our existing StateT and ExceptT modules, as well as several other imports from base . We’ll also go ahead and add two new types: Archive will be a record that holds our final parsed file archive, and ArchivedFile will hold the contents and metadata about each file that has been added to our archive.
| | {-# LANGUAGE DerivingStrategies #-} |
| | {-# LANGUAGE GeneralizedNewtypeDeriving #-} |
| | {-# LANGUAGE OverloadedStrings #-} |
| | |
| | module Archiver where |
| | |
| | import Control.Applicative |
| | import Control.Monad ( void , when ) |
| | import Data.ByteString ( ByteString ) |
| | import qualified Data.ByteString as ByteString |
| | import Data.Char ( isSeparator ) |
| | import Data.Text ( Text ) |
| | import qualified Data.Text as Text |
| | import qualified Data.Text.Encoding as Enc |
| | import ExceptT |
| | import StateT |
| | |
| | data Archive = Archive |
| | { archiveName :: Text |
| | , archivedFiles :: [ ArchivedFile ] |
| | } deriving stock ( Show ) |
| | |
| | data ArchivedFile = ArchivedFile |
| | { archivedFileName :: Text |
| | , archivedFileContents :: ByteString |
| | } deriving stock ( Show ) |
Next, let’s define the type for our archiving computations. Previous examples in this chapter have used type aliases to make the examples easier to follow, but for most real-world applications we’ll want to create a newtype wrapper around our monad transformer stack. This will let us add any additional type class instances we might want to define, and will also help us differentiate between our archival computations and other unrelated computations that happen to also use the same underlying monad transformer stack.
We’ll call our archival computation type Archiver . While we’re at it, we’ll also add a utility function to make it easier to run an Archiver action:
| | newtype Archiver a = Archiver |
| | {unArchiver :: StateT Text ( ExceptT Text IO ) a} |
| | deriving newtype ( Functor , Applicative , Monad , Alternative ) |
| | |
| | runArchiver :: Text -> Archiver a -> IO ( Either Text a) |
| | runArchiver inputText archiver = |
| | runExceptT $ evalStateT (unArchiver archiver) inputText |
You’ll notice in this example that we’re now nesting three different types of computation. Like the other parsers we have built in this chapter, we are composing StateT and ExceptT so that we can track a parse state and handle failures. Now we’re also adding in IO . This will allow us to interact with the filesystem so that we can read the contents of imported files as part of our Archiver actions.
Like our earlier examples, let’s start off the implementation of our Archiver parser by adding a parser to extract a character from the parse state:
| | parseChar :: Archiver Char |
| | parseChar = do |
| | parseText <- Archiver get |
| | case Text .uncons parseText of |
| | Nothing -> |
| | Archiver . liftStateT . throwError $ "end of input" |
| | Just (c, rest) -> do |
| | Archiver (put rest) |
| | pure c |
This function should look familiar by now, it’s similar to other implementations of the same function. The most notable difference is that all of our calls to any of our monad transformer actions now need to go through an Archiver constructor. In the case of throwError , we also need to lift the error into StateT before we wrap it in an Archiver .
The need to manually lift values, and to wrap and unwrap them, is a big ergonomic burden when using monad transformers. One option to address this would be to add helper functions that handle the work for any particular transformer stack, but that means we would end up rewriting the same helper functions every time we used a particular combination of transformers. It also means that any users of our API need to learn what helper functions we’ve defined, and possibly define new bespoke helpers if we’ve forgotten to add some common and useful ones.
Thankfully, there’s another approach we can take. We can define type classes to help us manage both lifting computations into our transformers, and to help us with wrapping and unwrapping common operations. Before we continue with our file archiver, let’s look at how we can define these type classes and use them to improve the ergonomics of our transformer stack.
Abstracting Over Lift with MonadTrans
The first type class that we’ll build to help make working with monad transformers easier is called MonadTrans , and it’s the type class that tells us something is a monad transformer. So, what is a monad transformer? We’ve already built a couple of examples, so let’s see if we can work backwards from ExceptT and StateT and figure out how we should define MonadTrans .
The first common feature of our two transformers was that they both allowed us to take any given monad and add some extra operations and effects to it. In the case of StateT that meant adding some mutable state. With ExceptT we added the ability to raise exceptions. In both cases though, we could add those operations to any other monad. The second common feature was that, in addition to whatever operations each transformer supported, they both offered us a way to lift an operation. In ExceptT we called the lifting operation succeed . When we defined StateT we called it liftStateT . Let’s look at their types:
| | succeed :: Monad m => m a -> ExceptT e m a |
| | liftStateT :: Monad m => m a -> StateT s m a |
Both of these two functions seem to take a monadic computation with the type m a and return a monadic computation that does the same action, but inside of the newly transformed monad. Since the type of these two functions is so similar, let’s use that as a starting point for our type class:
| | module MonadTrans where |
| | |
| | class MonadTrans t where |
| | lift :: Monad m => m a -> t m a |
Implementing this type class for StateT and ExceptT is pretty straightforward—we just need to call, or copy the definitions of, the lift functions we already defined. You can add these instances to your StateT and ExceptT modules respectively:
| | import MonadTrans |
| | |
| | instance MonadTrans ( StateT s) where |
| | lift m = StateT $ \ state -> (,state) <$> m |
| | import MonadTrans |
| | |
| | instance MonadTrans ( ExceptT e) where |
| | lift m = ExceptT ( Right <$> m) |
At one time, we would have been done with our definition of MonadTrans at this point. It turns out that lifting other monadic computations is the only basic operation that is universally shared across all monad transformers, so the version of MonadTrans that we defined in our example was quite similar to the definition used by the transformers library. Unfortunately, it turns out that this implementation has its own ergonomic difficulties that start to show up when we want to write code that uses nested monad transformers. Let’s look at a silly but illustrative example by writing a function that will evaluate some computation twice and return the results lifted into a monad transformer:
| | doSomethingTwice :: ( Monad m, MonadTrans t) => m a -> t m (a,a) |
| | doSomethingTwice something = do |
| | first <- lift something |
| | second <- lift something |
| | pure (first, second) |
Although it seems like this ought to compile, if we try to build this module we’ll get an error. The compiler doesn’t like using do notation, because it doesn’t think that our monad transformer is a monad. That’s for a good reason—although we clearly intend that a monad transformer should itself have a Monad instance, there’s nothing that forces that to be true. For example, let’s create a bad monad transformer named Decepticon to demonstrate the problem:
| | newtype Decepticon m a = Decepticon { getUnit :: () } |
| | |
| | instance MonadTrans Decepticon where |
| | lift _ = Decepticon () |
This definition of MonadTrans for our Decepticon satisfies the compiler, but it’s clearly not what we intended. For type classes like Applicative and Monad we use constraints to avoid this problem. Any type with a Monad instance must have an Applicative instance as well, and any type with an Applicative instance needs to also have a Functor instance. Unfortunately, with MonadTrans it’s not quite as easy to add a constraint. Let’s try it and see what happens:
| | class Monad t => MonadTrans t where |
| | lift :: Monad m => m a -> t m a |
If we try to load this into ghci we’ll get a somewhat confusing error:
| | MonadTrans.hs:4:29: error: |
| | • Expected kind ‘* -> *’, but ‘t’ has kind ‘*’ |
| | • In the type signature: lift :: Monad m => m a -> t m a |
| | In the class declaration for ‘MonadTrans’ |
| | | |
| | 4 | lift :: Monad m => m a -> t m a |
| | | ^^^^^ |
| | |
| | MonadTrans.hs:4:31: error: |
| | • Expecting one more argument to ‘m’ |
| | Expected a type, but ‘m’ has kind ‘* -> *’ |
| | • In the first argument of ‘t’, namely ‘m’ |
| | In the type signature: lift :: Monad m => m a -> t m a |
| | In the class declaration for ‘MonadTrans’ |
| | | |
| | 4 | lift :: Monad m => m a -> t m a |
| | | ^ |
| | Failed, no modules loaded. |
The compiler seems to be getting confused about the kind of t and m . Let’s add an explicit kind annotation to help the compiler, and hopefully get a better error message. A monad transformer has two type parameters: the monadic type that is embedded into the transformer, which should have the kind Type -> Type , and the type of value the monad transformer will compute, which should have kind Type . That means the kind of a monad transformer should be (Type -> Type) -> Type -> Type :
| | module MonadTrans where |
| | import Data.Kind |
| | |
| | class Monad t => MonadTrans (t :: ( Type -> Type ) -> Type -> Type ) where |
| | lift :: Monad m => m a -> t m a |
Now the error we get is a bit more useful:
| | [1 of 1] Compiling MonadTrans ( MonadTrans.hs, interpreted ) |
| | |
| | MonadTrans.hs:5:13: error: |
| | • Expecting one more argument to ‘t’ |
| | Expected kind ‘* -> *’, but ‘t’ has kind ‘(* -> *) -> * -> *’ |
| | • In the first argument of ‘Monad’, namely ‘t’ |
| | In the class declaration for ‘MonadTrans’ |
| | | |
| | 5 | class Monad t => MonadTrans (t :: (Type -> Type) -> Type -> Type) where |
| | | ^ |
| | Failed, no modules loaded. |
This error gets to the root of our problem: a monad transformer by itself doesn’t actually have a Monad instance. We only get a Monad instance after we apply some particular inner computation to our transformer. In other words, m should be a Monad , and (t m) should also be a Monad , but there’s no direct constraint on t by itself. We can reason about this using what we know about Monad , but the kind signatures help us too. Anything with a Monad instance needs to have the kind (Type -> Type) . That excludes t by itself, but we can see that the kind of m neatly slots into the first argument to t , giving us back a type with the kind (Type -> Type) . In pseudocode, you can imagine it like this:
| | -- t can't be a Monad because it doesn't have the kind (Type -> Type) |
| | t :: (Type -> Type) -> Type -> Type |
| | |
| | -- m has the right kind, so it can be a monad |
| | m :: Type -> Type |
| | |
| | -- In (t m), m "fills in" the (Type -> Type) argument |
| | t m = ((Type -> Type) -> Type -> Type) (Type -> Type) |
| | = Type -> Type -- The new type also has the right kind to be a Monad |
Since m isn’t a parameter to our type class, we can’t ordinarily reference it in a constraint. Thankfully, GHC offers a language extension that we can use for exactly this kind of scenario: QuantifiedConstraints . This extension uses universal quantification with the forall keyword inside of our type class constraints. Let’s add this extension and rewrite our type class one more time:
| | {-# LANGUAGE QuantifiedConstraints #-} |
| | module MonadTrans where |
| | |
| | class (forall m. Monad m => Monad (t m)) => MonadTrans t where |
| | lift :: Monad m => m a -> t m a |
| QuantifiedConstraints |
|---|
|
| The QuantifiedConstraints extension has been available since GHC 8.6.1. This extension isn’t enabled by default in either GHC2021 or Haskell2010 so you’ll need to enable it manually. This is a generally safe extension that shouldn’t cause problems with any existing code. |
Using QuantifiedConstraints , we can introduce a new type variable into the constraint, and use that to give the compiler some additional information that will allow it to prohibit some otherwise bad instances. For example, if we revisit our Decepticon example now, we’ll see that we get a type error since we can’t define a valid Monad instance for Decepticon m :
| | MonadTrans.hs:9:10: error: |
| | • Could not deduce (Monad (Decepticon m)) |
| | arising from the superclasses of an instance declaration |
| | from the context: Monad m |
| | bound by a quantified context at MonadTrans.hs:1:1 |
| | • In the instance declaration for ‘MonadTrans Decepticon’ |
| | | |
| | 9 | instance MonadTrans Decepticon where |
| | | ^^^^^^^^^^^^^^^^^^^^^ |
| | Failed, no modules loaded. |
At the same time, our doSomethingTwice function works exactly as we would have expected, because we’ve not told the compiler that any time we have a type t m where t is a MonadTransformer and m is a Monad , then t m must also be a Monad . Since t m must be a Monad then we are free to use do notation or any of the other capabilities we get from working with monads.
Transforming Monads with Class
Now that we’ve generalized the ability to lift one computation into another with lift , and we’ve added MonadTrans instances to ExceptT and StateT , we can address another one of the ergonomic problems that we’ve been dealing with as we’re using monad transformers: the need to explicitly lift functions written for one of our inner computations. Let’s take another look at parseChar from our Archiver example:
| | parseChar :: Archiver Char |
| | parseChar = do |
| | parseText <- Archiver get |
| | case Text .uncons parseText of |
| | Nothing -> |
| | Archiver . liftStateT . throwError $ "end of input" |
| | Just (c, rest) -> do |
| | Archiver (put rest) |
| | pure c |
In theory, our Archiver is supposed to represent a computation that can:
- Have mutable state
- Raise an exception
- Perform IO
As soon as we use it though, we can see that it’s not allowing us to do any of those effects directly. If we want to use mutable state, we need to use get or put , but those return a StateT that we need to pass to our Archiver constructor. Worse, when we want to throw an error we need to lift the ExceptT action into the StateT with liftStateT and then pass that to the Archiver constructor. If we want to do IO, the situation starts to get absurd. To write an Archiver action that reads a file from disk, we need to lift our IO action three separate times: once into ExceptT , again into StateT , and finally into Archiver . Thanks to MonadTrans we can make this code a little bit better by using lift rather than having to remember a different function to lift into each different transformer, but the result is still unsatisfying:
| | import MonadTrans |
| | |
| | readArchiveContents :: FilePath -> Archiver ByteString |
| | readArchiveContents = |
| | Archiver . lift . lift . ByteString .readFile |
The problem that we have here is that the basic operations we’ve defined for our side effects, like get and put or throwError , are each defined for a particular type of computation. We define get specifically for StateT , and we define throwError specifically for ExceptT . This is all well and good as long as these functions are the basic operations we need for just those particular types, but using monad transformers means that we can define many different types that all use those same basic operations. Now get isn’t just a basic operation for StateT , but it’s also a basic operation for any other monad transformer that has embedded StateT .
One way that we can address this is to write some basic operations for each type that we define. For example, we could write variations of get , put , throwError , and readFile for Archiver and use them instead of having to lift the operations every time we need them:
| | archiveGet :: Archiver Text |
| | archiveGet = Archiver get |
| | |
| | archivePut :: Text -> Archiver () |
| | archivePut = Archiver . put |
| | |
| | archiveError :: Text -> Archiver a |
| | archiveError text = Archiver $ liftStateT (throwError text) |
| | |
| | archiveReadFile :: FilePath -> Archiver ByteString |
| | archiveReadFile = Archiver . lift . lift . ByteString .readFile |
This is a completely viable approach, and it’s sometimes the way we want to approach building our applications. It gives us precise control over the actions that can happen inside of our computation, and gives us some flexibility to refactor the implementation details of our side effects later with minimal impact to the rest of our application. This approach also has some down sides. Most notably, it means that each time we want to use some other StateT or ExceptT action we’ll need to either lift it, or add a new wrapper.
Another option that we have is to decouple the particular monad transformers from their operations using type classes. Let’s look at an example of how we can do this with StateT by creating a new module called MonadState . We’ll begin by importing a few modules:
| | {-# LANGUAGE MultiParamTypeClasses #-} |
| | {-# LANGUAGE FlexibleInstances #-} |
| | |
| | module MonadState ( |
| | MonadState (..), |
| | module X , |
| | ) where |
| | |
| | import ExceptT |
| | import MonadTrans |
| | import StateT as X hiding (get, put) |
| | import qualified StateT as State |
Next, let’s try to define a new type class called MonadState . We need to represent any monadic computation of type m that has a mutable state of any type s :
| | class Monad m => MonadState s m where |
| | get :: m s |
| | put :: s -> m () |
We can easily create an instance of MonadState for StateT by re-using the get and put instances that we defined in the StateT module:
| | instance Monad m => MonadState s ( State . StateT s m) where |
| | put = State .put |
| | get = State .get |
We can also save our users from needing to manually lift calls to get and put when a StateT is nested inside of some of our other monad transformers. For example, we can preemptively add an instance of MonadState for ExceptT as long as the monad embedded into it has a MonadState instance:
| | instance MonadState s m => MonadState s ( ExceptT e m) where |
| | put = lift . put |
| | get = lift get |
Now, if we want to create a transformer stack where we are embedding a StateT inside of an ExceptT , we can call get or put directly without needing to use lift or succeed . Let’s compare two small examples to see this in action. Imagine we wanted to write a simple guessing game. Each round, the user will guess the current state. The game will set the next state to whatever their guess was, and then it will return True if they guessed the state. Without MonadState we could write that with manual calls to lift , but we’re leaking the implementation detail that GuessingGame is using a monad transformer, and forcing our user to deal with that rather than working with the state we’re handling directly.
| | module MonadStateDemo where |
| | import StateT |
| | import ExceptT |
| | import MonadTrans |
| | |
| | type GuessingGame a = ExceptT String ( StateT String IO ) a |
| | |
| | evalGame :: |
| | String -> GuessingGame a -> IO ( Either String a) |
| | evalGame input = |
| | flip StateT .evalStateT input . runExceptT |
| | |
| | guessTheState :: String -> GuessingGame Bool |
| | guessTheState guess = do |
| | answer <- lift get |
| | lift $ put guess |
| | pure $ guess == answer |
If we use MonadState instead, we can preserve the same application logic, but now we don’t need to lift our function state operations. This makes the API much nicer:
| | module MonadStateDemo where |
| | import MonadState |
| | import ExceptT |
| | |
| | type GuessingGame a = ExceptT String ( StateT String IO ) a |
| | |
| | guessTheState :: String -> GuessingGame Bool |
| | guessTheState guess = do |
| | answer <- get |
| | put guess |
| | pure $ guess == answer |
The benefits of this approach go deeper than just avoiding explicit calls to lift. Since our basic operations like get and put now depend on the MonadState type class rather than a particular type, we can refactor our program to make GuessingGame newtype without having to change guessTheState at all. We can just ask the compiler to derive an instance of MonadState for us:
| | {-# LANGUAGE DerivingStrategies #-} |
| | {-# LANGUAGE GeneralizedNewtypeDeriving #-} |
| | module MonadStateDemo where |
| | import MonadState |
| | import ExceptT |
| | |
| | newtype GuessingGame a = |
| | GuessingGame { runGame :: ExceptT String ( StateT String IO ) a } |
| | deriving newtype ( Functor , Applicative , Monad , MonadState String ) |
| | |
| | guessTheState :: String -> GuessingGame Bool |
| | guessTheState guess = do |
| | answer <- get |
| | put guess |
| | pure $ guess == answer |
This is a pretty substantial refactor given that we had to change nothing about our implementation at all. As you can imagine, as our programs grow larger, the overhead of changing the way we represent our types can be large, so this approach to abstraction can save a lot of refactoring effort.
We still have a bit of a problem though. Before we dive into the details, let’s make a quick change to our program. Imagine that users are playing our guessing game, decide it’s too difficult, and ask us to make two changes. First, the state should stay the same no matter how many times the game is played. Second, instead of having to guess the exact state, a user should win if they guess how many characters are in the state. This seems like it should make our program much simpler, so let’s try to make the changes:
| | guessTheState :: Int -> GuessingGame Bool |
| | guessTheState guess = do |
| | answer <- length <$> get |
| | pure $ guess == answer |
It turns out that this small change results in a pretty big compiler error. If we try to build this version of the program, we’ll get a couple of errors:
| | MonadStateDemo.hs:23:13: error: |
| | • Ambiguous type variable ‘t0’ arising from a use of ‘length’ |
| | prevents the constraint ‘(Foldable t0)’ from being solved. |
| | Probable fix: use a type annotation to specify what ‘t0’ should be. |
| | These potential instances exist: |
| | instance Foldable (Either a) -- Defined in ‘Data.Foldable’ |
| | instance Foldable Maybe -- Defined in ‘Data.Foldable’ |
| | instance Foldable ((,) a) -- Defined in ‘Data.Foldable’ |
| | ...plus two others |
| | ...plus 29 instances involving out-of-scope types |
| | (use -fprint-potential-instances to see them all) |
| | • In the first argument of ‘(<$>)’, namely ‘length’ |
| | In a stmt of a 'do' block: answer <- length <$> get |
| | In the expression: |
| | do answer <- length <$> get |
| | pure $ guess == answer |
| | | |
| | 23 | answer <- length <$> get |
| | | ^^^^^^ |
| | |
| | MonadStateDemo.hs:23:24: error: |
| | • Ambiguous type variables ‘t0’, ‘a0’ arising from a use of ‘get’ |
| | prevents the constraint ‘(MonadState |
| | (t0 a0) GuessingGame)’ from being solved. |
| | Probable fix: use a type annotation to specify what ‘t0’, |
| | ‘a0’ should be. |
| | These potential instance exist: |
| | instance MonadState String GuessingGame |
| | -- Defined at MonadStateDemo.hs:19:50 |
| | • In the second argument of ‘(<$>)’, namely ‘get’ |
| | In a stmt of a 'do' block: answer <- length <$> get |
| | In the expression: |
| | do answer <- length <$> get |
| | pure $ guess == answer |
| | | |
| | 23 | answer <- length <$> get |
The compiler is telling us that it can’t figure out what type of value should be returned by get . Since it doesn’t know what kind of value get is returning, it also doesn’t know what instance of Foldable should be used for length . If we can solve the first problem—getting the compiler to understand what type should be returned by get —then the second problem will solve itself.
The reason that we’re getting this error is that the MonadState type class is defined with two parameters: the state value, s , and the monad, m . The way we’ve defined the class, there’s no relationship between them. As the programmer, it’s obvious to us that the type of state for StateT String is going to be String , but we’re not giving the compiler enough information to figure that out. We can use a type application to help the compiler out:
| | {-# LANGUAGE TypeApplications #-} |
| | |
| | guessTheState :: Int -> GuessingGame Bool |
| | guessTheState guess = do |
| | answer <- length <$> get @ String |
| | pure $ guess == answer |
This will get our program compiling again, but now we’re hardly better off than when we had to call lift each time we wanted to use an operation that acted on the state. It would be better if we could tell the compiler that whenever it sees a type like MonadState String (StateT String) it should be able to derive the type of the state from the type of the computation. There are two ways that we can solve this problem. Later on in this book you’ll learn about type families, an extremely flexible tool that will let you solve problems like this. For now, we’ll focus on the approach favored by the mtl library: functional dependencies .
A functional dependency is a way for us to tell the compiler that some types in a multiparameter type class have a direct dependency on some other types. For example, we can say that the type of the state in a MonadState instance depends on the type of the monad. To do that, we’ll need to add two new language extensions: FunctionalDependencies will allow us to create a functional dependency, and UndecidableInstances will allow us to write some type class instances that are normally prohibited, because they could cause the compiler’s type checker to not be able to check the type of the instances.
| FunctionalDependencies |
|---|
|
| The FunctionalDependencies extension has been available since GHC 6.8.1. It isn’t enabled by default in either GHC2021 or Haskell2010 so you’ll need to enable it manually. This extension implies the MultiParamTypeClasses extension, so you won’t need to enable it explicitly if you’ve already enabled FunctionalDependencies . Since FunctionalDependencies substantially changes the behavior of type classes, it’s typically enabled on a case-by-case basis for modules that need the feature, rather than being enabled project wide. You only need to enable the extension in the module where you define the a type class with functional dependencies. It’s not needed when you only want to create a new instance. |
| UndecidableInstances |
|---|
|
| The UndecidableInstances extension has been available since GHC 6.8.1. This extension isn’t enabled by default in either GHC2021 or Haskell2010 so you’ll need to enable it manually. Although this extension is safe in the sense that it should not cause any previously existing code to stop working, it’s generally not a good idea to enable this extension for an entire project. Instead, you should enable this extension on a case-by-case basis when it’s needed in a particular module. The UndecidableInstances extension lifts restrictions that ensure the type checker can actually complete type checking type class instances. These checks are helpful more often than not, and prevent you from writing code that might cause the compiler to hang during type checking. You should only enable the extension when you actually need to relax these checks. |
With our new language extension added, we can update our type class to add the functional dependency:
| | {-# LANGUAGE FunctionalDependencies #-} |
| | {-# LANGUAGE UndecidableInstances #-} |
| | |
| | class Monad m => MonadState s m | m -> s where |
| | get :: m s |
| | put :: s -> m () |
The part of the instance declaration after the vertical pipe ( | ) is our functional dependency. When we say | m -> s we’re creating a functional dependency that tells the compiler that the type of m should uniquely determine the type of s .
With this change in place, our simple definition of guessTheState will work without any need for a type application or annotation. Since the type of the state depends on the type of the monad, the compiler is able to figure out that it must be a String .
| | {-# LANGUAGE DerivingStrategies #-} |
| | {-# LANGUAGE GeneralizedNewtypeDeriving #-} |
| | module EffectiveHaskell.Chapter13.MonadStateDemo.V3 where |
| | |
| | import EffectiveHaskell.Chapter13.MonadState |
| | import EffectiveHaskell.Chapter13.ExceptT |
| | |
| | newtype GuessingGame a = |
| | GuessingGame { runGame :: ExceptT String ( StateT String IO ) a } |
| | deriving newtype ( Functor , Applicative , Monad , MonadState String ) |
| | |
| | evalGame :: String -> GuessingGame a -> IO ( Either String a) |
| | evalGame input = flip evalStateT input . runExceptT . runGame |
| | guessTheState :: Int -> GuessingGame Bool |
| | guessTheState guess = do |
| | answer <- length <$> get |
| | pure $ guess == answer |
Before we move on, let’s celebrate our effort and refactoring with a quick look at some of our new code running live in ghci :
| | λ> evalGame "four" $ guessTheState 4 |
| | Right True |
| | λ> evalGame "four" $ guessTheState 3 |
| | Right False |
MonadError
The same ideas that we used to build MonadState can be applied to any other problem where we might have several different types that implement a particular effect. Another example of this is failure. You’ve already seen examples of using MonadFail to handle some failures when building your parser. Although it’s handy in some cases, MonadFail is intended to be used to handle failing pattern matches. It’s not intended for more sophisticated error handling.
You’ve already seen how ExceptT gives us more control over how we define and handle errors. We can take these same capabilities and define them in a type class so that we have a general purpose way of talking about types that support exceptions and robust error handling. This type class is named MonadError in the mtl . We can implement MonadError using the same patterns we used for MonadState :
| | {-# LANGUAGE FunctionalDependencies #-} |
| | {-# LANGUAGE UndecidableInstances #-} |
| | {-# LANGUAGE FlexibleInstances #-} |
| | |
| | module MonadError ( |
| | MonadError (..), |
| | module X , |
| | ) where |
| | |
| | import ExceptT as X hiding (catchError, throwError) |
| | import qualified ExceptT as Except |
| | import MonadTrans |
| | import ReaderT |
| | import StateT |
| | |
| | class Monad m => MonadError e m | m -> e where |
| | throwError :: e -> m a |
| | catchError :: m a -> (e -> m a) -> m a |
| | |
| | instance Monad m => MonadError e ( Except . ExceptT e m) where |
| | throwError = Except .throwError |
| | catchError = flip Except .catchError |
| | |
| | instance MonadError e m => MonadError e ( StateT s m) where |
| | throwError = lift . throwError |
| | catchError action handler = |
| | StateT $ \ s -> |
| | let innerAction = runStateT action s |
| | liftedHandler e = runStateT (handler e) s |
| | in catchError innerAction liftedHandler |
Tagless Final Encoding
Now that we have a general way to use functions like get and put , and the compiler is better able to keep track of the type of the state based on the monad it’s associated with, we have one more opportunity to add an additional level of flexibility. Instead of picking any particular monad that our code should run in, we can instead use constraints to tell the compiler what capabilities our code needs. For example, our guessing game doesn’t need to raise any exceptions, nor does it need to do any IO. We can run the guessing game inside of any computation, so long as it has mutable state, and that state has a Foldable instance we can use to get the length of the state. Let’s try rewriting our original guesser to be more generic using these constraints:
| | genericGuesser :: ( Foldable t, MonadState (t a) m) => Int -> m Bool |
| | genericGuesser guess = do |
| | answer <- length <$> get |
| | pure $ guess == answer |
Using constraints like this gives us even more flexibility, because now we’re not only able to refactor the type of computation that our code runs in, we can also use the same code with different types of computation. Let’s create a second guessing game type that will hold a list of numbers instead of a String :
| | newtype GuessingGame2 a = |
| | GuessingGame2 { runGame2 :: ExceptT String ( StateT [ Int ] IO ) a } |
| | deriving newtype ( Functor , Applicative , Monad , MonadState [ Int ]) |
We can only use our original guessTheState function with our original GuessingGame type, but genericGuesser can be used with either of these types of computation, or even types that we haven’t thought of yet.
This constraint-first approach to representing applications with type classes is called tagless final encoding . In the particular case where we’re using tagless final encoding with monad transformers, it’s often referred to as mtl style . That’s because mtl is the name of the popular library that provides type classes like MonadState that work with the concrete monad transformers defined in the transformers library. When a specific term is needed to differentiate it from MTL style, you’ll sometimes hear the approach to writing monad transformer code explicitly using lift and the transformers themselves called direct style .
Writing programs using MTL style has a mixture of advantages and disadvantages, so it’s useful to think about the requirements of your particular application. MTL style offers clear advantages for flexibility. You can refactor your application more easily, and you can more easily re-use code that was written in MTL style in ways that the author might not have foreseen. MTL style is also a useful way to handle dependency injection in Haskell applications. Using MTL style makes it easier to write tests that select a particular computation that was designed for testing. The same flexibility that makes MTL style useful can also be a burden at times. The biggest disadvantage is that using MTL style means that you can’t make assumptions about the side effects that might be executed by your code. Using a direct style that forces a particular computation that you have written means that you have more control over the behavior of your program. Direct style also lends itself to more clear and concise error messages, and in larger applications it can reduce the time it takes to compile your programs.
MonadIO
Before we revisit our Archiver tool, let’s look at one last type class that is frequently used with tagless final style programs in general, and with monad transformers in particular: MonadIO . This class is defined for us in base at Control.Monad.IO.Class , but it’s simple enough that we can recreate the entire class in just a few lines of code:
| | module MonadIO where |
| | |
| | class Monad m => MonadIO m where |
| | liftIO :: IO a -> m a |
| | |
| | instance MonadIO IO where |
| | liftIO = id |
Writing instances for MonadIO for monad transformers tends to be straightforward. Let’s look at the instances for StateT and ExceptT :
| | import EffectiveHaskell.Chapter13.MonadIO |
| | instance MonadIO m => MonadIO ( StateT s m) where |
| | liftIO = lift . liftIO |
| | import EffectiveHaskell.Chapter13.MonadIO |
| | instance MonadIO m => MonadIO ( ExceptT s m) where |
| | liftIO = lift . liftIO |
As you can see, MonadIO isn’t doing much more than calling lift . The value of MonadIO is not in having sophisticated implementations of liftIO , but in the ability to use tagless final style functions to create IO actions that are polymorphic and work with IO actions or with any monad transformer that, directory or indirectly, embeds IO . For example, imagine that we wanted to write a function that added some basic logging that would tell us when a function was called. Writing to the screen requires that we be able to do IO, but with MonadIO we can make our function work for any type that embeds IO :
| | runWithLog :: MonadIO m => (a -> m b) -> a -> m b |
| | runWithLog action val = do |
| | liftIO $ putStrLn "Running the function..." |
| | result <- action val |
| | liftIO $ putStrLn "Finished running the function" |
| | pure result |
If we load this function into ghci we can see that it’s usable with any monad transformer stack that embeds IO :
| | λ s = const (pure "hello state" ) :: a -> StateT String IO String |
| | λ evalStateT (runWithLog s 100) "" |
| | Running the function... |
| | Finished running the function |
| | "hello state" |
| | |
| | λ e = const (pure "hello except" ) :: a -> ExceptT String IO String |
| | λ runExceptT $ runWithLog e 100 |
| | Running the function... |
| | Finished running the function |
| | Right "hello except" |
| | |
| | λ i = const (pure "hello IO" ) :: a -> IO String |
| | λ runWithLog i 100 |
| | Running the function... |
| | Finished running the function |
| | "hello IO" |
| | |
| | λ n = const (pure "hello nested" ) :: |
| | a -> StateT String ( ExceptT String ( StateT String IO )) String |
| | λ > evalStateT (runExceptT (evalStateT (runWithLog n 100) "" )) "" |
| | Running the function... |
| | Finished running the function |
| | Right "hello nested" |
Deriving a Better Archiver
Now that we’ve added the extra type classes to make it easier to work with monad transformer stacks, let’s revisit our Archiver application again, and update it to work with the new type classes that we’ve just added. The first change that we’ll make is to the definition of Archiver itself. The way that we’re representing the stack of monad transformers doesn’t need to change, but we can now realize one of the biggest benefits of moving toward our type class-based approach to working with transformers: deriving instances of all of the relevant type classes automatically. Since we’re using a newtype wrapper to define Archiver , we can benefit from the work we’ve done to get all of the instances we need for free. Now that we’ve done the work, let’s take a look at the final monad transformer-based archiver tool. You’ll notice as you review this example that we’re able to mix basic operations like get and put with exceptions and IO actions all inside of a single Archiver computation:
| | {-# LANGUAGE DerivingStrategies #-} |
| | {-# LANGUAGE GeneralizedNewtypeDeriving #-} |
| | {-# LANGUAGE OverloadedStrings #-} |
| | |
| | module ClassyArchiver where |
| | |
| | import Control.Applicative |
| | import Control.Monad ( void , when ) |
| | import Data.ByteString ( ByteString ) |
| | import qualified Data.ByteString as ByteString |
| | import Data.Char ( isSeparator ) |
| | import Data.Text ( Text ) |
| | import qualified Data.Text as Text |
| | import qualified Data.Text.Encoding as Enc |
| | import MonadError |
| | import MonadIO |
| | import MonadState |
| | |
| | data Archive = Archive |
| | { archiveName :: Text |
| | , archivedFiles :: [ ArchivedFile ] |
| | } |
| | deriving stock ( Show ) |
| | |
| | data ArchivedFile = ArchivedFile |
| | { archivedFileName :: Text |
| | , archivedFileContents :: ByteString |
| | } |
| | deriving stock ( Show ) |
| | |
| | newtype Archiver a = Archiver |
| | {unArchiver :: StateT Text ( ExceptT Text IO ) a} |
| | deriving newtype |
| | ( Functor |
| | , Applicative |
| | , Monad |
| | , Alternative |
| | , MonadState Text |
| | , MonadError Text |
| | , MonadIO |
| | ) |
| | |
| | runArchiver :: Text -> Archiver a -> IO ( Either Text a) |
| | runArchiver inputText archiver = |
| | runExceptT $ evalStateT (unArchiver archiver) inputText |
| | |
| | parseChar :: Archiver Char |
| | parseChar = do |
| | parseText <- get |
| | case Text .uncons parseText of |
| | Nothing -> |
| | throwError "end of input" |
| | Just (c, rest) -> do |
| | put rest |
| | pure c |
| | |
| | dropSpaces :: Archiver () |
| | dropSpaces = void $ many (expectChar ' ' ) |
| | |
| | isNewline :: Char -> Bool |
| | isNewline = (== ' \n ') |
| | |
| | e xpect :: Eq a => Archiver a -> a -> Archiver () |
| | expect getActual expected = do |
| | actual <- getActual |
| | when (expected /= actual) $ do |
| | throwError "expectation violated" |
| | |
| | expectChar :: Char -> Archiver () |
| | expectChar = expect parseChar |
| | |
| | expectText :: Text -> Archiver () |
| | expectText expected = do |
| | stripped <- Text .stripPrefix expected <$> get |
| | case stripped of |
| | Nothing -> throwError "missing expected string" |
| | Just rest -> put rest |
| | |
| | takeUntil :: ( Char -> Bool ) -> Archiver Text |
| | takeUntil predicate = do |
| | (result, rest) <- Text .break predicate <$> get |
| | put rest |
| | pure result |
| | |
| | word :: Archiver Text |
| | word = do |
| | nextWord <- takeUntil ( \ s -> isSeparator s || isNewline s) |
| | void . optional $ expectChar ' \n ' < |> dropSpaces |
| | when ( Text .null nextWord) $ |
| | throwError "end of input" |
| | pure nextWord |
| | |
| | quotedString :: Archiver Text |
| | quotedString = do |
| | expectChar '"' |
| | quotedText <- takeUntil (== '"' ) |
| | expectChar '"' |
| | pure quotedText |
| | |
| | restOfLine :: Archiver Text |
| | restOfLine = remainderOfLine <|> remainderOfText |
| | where |
| | remainderOfLine = do |
| | txt <- takeUntil isNewline |
| | expectChar ' \n ' |
| | pure txt |
| | remainderOfText = get |
| | |
| | dropEmptyLines :: Archiver () |
| | dropEmptyLines = |
| | void $ many $ dropSpaces >> expectChar ' \n ' |
| | |
| | p a rseIndentedLine :: Int -> Archiver Text |
| | parseIndentedLine indentLevel = do |
| | expectText $ Text .replicate indentLevel " " |
| | restOfLine |
| | |
| | runSubparser :: Archiver a -> Text -> Archiver a |
| | runSubparser action subparserState = do |
| | oldText <- get |
| | put subparserState |
| | result <- action |
| | put oldText |
| | pure result |
| | |
| | parseBlock :: Archiver a -> Archiver a |
| | parseBlock blockParser = |
| | dropEmptyLines >> getBlock >>= runSubparser blockParser |
| | where |
| | getBlock = do |
| | firstLineSpacing <- takeUntil (not . isSeparator) |
| | let indentation = Text .length firstLineSpacing |
| | firstLine <- restOfLine |
| | restOfBlock <- many (dropEmptyLines >> parseIndentedLine indentation) |
| | pure $ Text .unlines (firstLine : restOfBlock) |
| | |
| | parseImportStatement :: Archiver ArchivedFile |
| | parseImportStatement = do |
| | expectText "import" |
| | dropSpaces |
| | path <- quotedString |
| | dropSpaces |
| | expectChar ' \n ' |
| | contents <- liftIO $ ByteString .readFile ( Text .unpack path) |
| | pure $ ArchivedFile path contents |
| | |
| | parseNewFileStatement :: Archiver ArchivedFile |
| | parseNewFileStatement = do |
| | expectText "new-file" |
| | dropSpaces |
| | path <- quotedString |
| | dropSpaces |
| | expectText ": \n " |
| | body <- Enc .encodeUtf8 <$> parseBlock get |
| | pure $ ArchivedFile path body |
| | |
| | parseArchiveStatements :: Archiver [ ArchivedFile ] |
| | parseArchiveStatements = |
| | many $ dropEmptyLines >> (parseImportStatement <|> parseNewFileStatement) |
| | |
| | parseArchive :: Archiver Archive |
| | parseArchive = do |
| | expectText "archive" |
| | dropSpaces |
| | archiveName <- quotedString |
| | expectText ": \n " |
| | files <- parseBlock parseArchiveStatements |
| | pure $ Archive archiveName files |