We’ve dealt with parsing several times in this book, most recently in the previous chapter where we focused on building a parser to extract data created by our FilePack tool. In all of these examples, we’ve addressed the parsing problems we were trying to solve specifically, tailoring our code to the particular application we wanted to build. Narrowly focusing on a particular problem let us keep the size of our application small, but it also meant that we’ve re-written similar code several times. That’s a good indication that we might want to look at ways that we can abstract away parts of the problem to avoid rework in the future.
Let’s start thinking about how we can abstract away parts of a parser by re-visiting the definition of the parser we built in the previous chapter:
| | newtype FilePackParser a = FilePackParser |
| | { runParser :: BS . ByteString -> Either String (a, BS . ByteString ) } |
The definition of FilePackParser that we settled on in the last chapter represents a parser computation as a function from some previous parse state to an error message or a value and a new parse state. The first thing that we can do to make this a bit more re-usable is to allow our user to pick their own types for the internal state and for errors. That way, if a user decides they want to parse Text or String data, or use a sum type to differentiate between different errors, they can do it without needing to write a brand new parser type:
| | newtype Parser e s a = Parser |
| | { runParser :: s -> Either e (a, s) } |
| | |
| | type FilePackParser = Parser String BS . ByteString |
Making the error and internal state type parameters is a clear benefit to the flexibility of our parser, and as you can see in the example, it doesn’t require that we give up a more ergonomic definition of the particular parser we might want to build. We can use type aliases to preserve the ergonomics of working with a very general type like Parser with some particular types applied.
Now that we’ve stripped away some details, like the specific types of the internal state and the errors, we can start to look at the shape of a parser and think about where we might be able to break it down into more fundamental abstractions. When we do this, it turns out that our Parser type is really a combination of two other monadic computations: the Either monad that we use for handling errors, and a monad that we haven’t seen before, State . Before we dive into how we can combine Either and State to make a parser, let’s take a quick detour to learn about the State monad. Understanding how State works independently of parsing will help us better understand how to use it as a building block.
The State Monad
The State monad gives us a way to represent mutable state in Haskell programs. Although State is widely used in Haskell programs, we rarely encounter it by itself. The mtl and transformers libraries export a couple of different variations of State , but you’re more likely to encounter it behind the scenes in a type like Parser rather than working with it directly. In fact, you’ve worked with a variation of State quite extensively already in this book: IO is essentially a version of State where the mutable state is a reference to the external state of the real world.
Fundamentally, State is a function from an old state to a value and a new state. After working with FilePackParser extensively in the last chapter, the definition of State should be familiar, so let’s look at a complete implementation of a State module and then walk through the ways that this is different than our earlier parsers:
| | module State where |
| | |
| | newtype State s a = State {runState :: s -> (a, s)} |
| | |
| | instance Functor ( State s) where |
| | fmap f g = State $ \ lastState -> |
| | let (val, nextState) = runState g lastState |
| | in (f val, nextState) |
| | |
| | instance Applicative ( State s) where |
| | pure val = State $ \ s -> (val, s) |
| | f <*> g = State $ \ oldState -> |
| | let (h, funcState) = runState f oldState |
| | (val, valState) = runState g funcState |
| | in (h val, valState) |
| | |
| | instance Monad ( State s) where |
| | return = pure |
| | f >>= g = State $ \ oldState -> |
| | let (val, valState) = runState f oldState |
| | in runState (g val) valState |
| | |
| | evalState :: State s a -> s -> a |
| | evalState stateAction initialState = |
| | fst $ runState stateAction initialState |
| | |
| | execState :: State s a -> s -> s |
| | execState stateAction initialState = |
| | snd $ runState stateAction initialState |
| | |
| | put :: s -> State s () |
| | put state = State $ \ _ -> ((), state) |
| | |
| | get :: State s s |
| | get = State $ \ state -> (state, state) |
The most obvious difference between State and our parser examples is that we’re no longer handling any possibility of failure. Our Functor , Applicative , and Monad instances are a bit simpler now that they don’t need to deal with error handling, but otherwise they are the same as the version we wrote for File PackParser .
A less obvious difference is that we’ve included two functions that work with State : get and put . When we were building our parser from scratch, we created quite a few different parser actions that directly accessed the parse state. Usually these functions looked something like this:
| | someParserAction :: State s a |
| | someParserAction = State $ \ oldState -> |
| | let newState = transformState oldState |
| | in (makeSomeValue oldState, newState) |
In other words, most of our parser functions took advantage of the implementation details of the parser itself to get the old state and put a new state by writing the step function manually. With get and put we won’t need to directly call a State constructor. Instead, we can use do notation:
| | someParserAction :: State s a |
| | someParserAction = do |
| | oldState <- get |
| | put (transformState oldState) |
| | pure (makeSomeValue oldState) |
Being able to use get and put instead of directly constructing a State value might seem like a small thing that doesn’t have any real impact, but it turns out to be an important part of being able to use monad transformers to compose different monadic effects. That’s because we can combine monad transformers in many different ways, and we frequently will want to write code that should be re-usable no matter how we’ve brought State into the picture. As you’ll see later in this chapter, if we’re directly accessing the State constructor we end up severely limiting the flexibility that we can get from our transformers.
Before we move on and look at some bigger examples of how we can use State , let’s try a small example. We’ll write a function that will let us build up some lines of text, with each new line of text being indented more than the previous line. We’ll keep the current level of indentation in the mutable state:
| | module BasicStateDemo where |
| | import State |
| | |
| | appendLineWithIndent :: String -> String -> State Int String |
| | appendLineWithIndent message previousMessage = do |
| | indentLevel <- get |
| | let |
| | nextIndentLevel = indentLevel + 2 |
| | indent = replicate nextIndentLevel ' ' |
| | output = previousMessage <> indent <> message <> " \n " |
| | put nextIndentLevel |
| | pure output |
| | |
| | appendLineDemo :: IO () |
| | appendLineDemo = |
| | putStrLn $ evalState message 0 |
| | where |
| | message = |
| | appendLineWithIndent "hello" "" |
| | >>= appendLineWithIndent "world" |
| | >>= appendLineWithIndent "love," |
| | >>= appendLineWithIndent "George" |
If we load this up into ghci we can see that our stateful function does exactly what we’d expect:
| | λ appendLineDemo |
| | hello |
| | world |
| | love, |
| | George |
Stateful Parsing
Now that we’ve learned a bit about State and how it works on its own, let’s look at how we can use State to make our lives easier when we’re writing parsers. We’ve seen enough examples now to know that we can’t have a parser without needing to deal with parse failures. Although we dropped support for error handling when we defined State , we can still write a State -based parser that works the way we want it to. Since a State computation can return any kind of result that it likes, we can have our stateful computation output an Either value that will tell us if we encountered an error. Let’s see if we can use this to write a basic parser we can use to parse someone’s name:
| | module BasicStateDemo where |
| | import Data.Text ( Text ) |
| | import Data.Char ( isSpace ) |
| | import qualified Data.Text as Text |
| | import State |
| | |
| | type Parser a = State Text ( Either Text a) |
| | |
| | data FullName = FullName |
| | { first :: Text |
| | , middle :: Text |
| | , last :: Text |
| | } deriving Show |
| | |
| | takeUntil :: ( Char -> Bool ) -> Parser Text |
| | takeUntil predicate = do |
| | oldState <- get |
| | let (nextVal, rest) = Text .break predicate oldState |
| | put rest |
| | pure (pure nextVal) |
| | |
| | dropChar :: Parser () |
| | dropChar = do |
| | parseState <- get |
| | let newState = Text .tail parseState |
| | put newState |
| | pure ( Right ()) |
| | |
| | word :: Parser Text |
| | word = do |
| | nextWord <- takeUntil isSpace |
| | _ <- dropChar |
| | pure nextWord |
| | |
| | parseFullName :: Parser FullName |
| | parseFullName = do |
| | firstName <- word |
| | middleName <- word |
| | lastName <- word |
| | pure $ do |
| | firstName' <- firstName |
| | middleName' <- middleName |
| | lastName' <- lastName |
| | pure $ FullName firstName' middleName' lastName' |
It works…kind of. We’ve written a parser that technically meets our requirements: it’s using State for handling the internal parse state, and Either for handling parse errors, but this has come at a pretty high usability cost. The reason this approach ends up with code that feels so awkward to use is that we’re accustomed to having a single unified interface for all of the effects that happen in a computation. When we use do notation, we don’t want to think about each separate type of effect independently. When we defined Applicative and Monad instances from scratch, we could deal with all of the different effects all at once. When we try to compose effects, we’re feeling the pain of having to do this manually.
Most of the tedium that we’re experiencing with this parser comes from the fact that we have two nested monads. Everything that we want to do needs to be wrapped and unwrapped twice. Once to deal with the outer State action, and again to deal with the inner Either value. When we built out a parser from scratch, we didn’t need to deal with that because our Functor , Applicative , and Monad instances all managed both the mutable state and error handling at the same time.
Just because we’re now using State and Either together doesn’t mean that we have to give up having an interface that lets us deal with them together. One way that we can do this is to make Parser a newtype wrapper and add our own Functor , Applicative , and Monad instances. Unlike our earlier stand-alone parser, this time we won’t have to deal with the details of implementing State or error handing ourselves. Instead, we can rely on State and Either to handle their own effects, and our instances will only need to coordinate the interaction between the two. Let’s look at an example of how we can do this:
| | module FailingStatefulParser where |
| | import Control.Monad |
| | import Data.Char ( isSpace ) |
| | import Data.Text ( Text ) |
| | import qualified Data.Text as Text |
| | import State ( State ) |
| | import qualified State |
| | |
| | newtype Parser a = Parser |
| | {runParser :: State Text ( Either String a)} |
| | |
| | evalParser :: Parser a -> Text -> Either String a |
| | evalParser = State .evalState . runParser |
| | |
| | parse :: Parser a -> Text -> ( Either String a, Text ) |
| | parse = State .runState . runParser |
| | |
| | instance Functor Parser where |
| | fmap f parser = |
| | Parser $ (fmap . fmap) f (runParser parser) |
| | |
| | instance Applicative Parser where |
| | pure a = Parser $ (pure . pure) a |
| | f <*> a = Parser $ do |
| | f' <- runParser f |
| | a' <- runParser a |
| | pure $ f' <*> a' |
| | |
| | instance Monad Parser where |
| | return = pure |
| | a >>= f = Parser $ do |
| | val <- runParser a |
| | case val of |
| | Left err -> pure ( Left err) |
| | Right val' -> runParser (f val') |
The improved instances are only half of what we need to do if we want to present a unified interface into both ‘State‘ and ‘Either‘. We will also need a way to run both State and Either actions. Functions like get and put will still return State actions, and that means we can’t use them directly, since the rest of our code will be expecting Parser actions. There are two different approaches we can take. The first option is to create Parser -specific implementations of the basic operations that are supported by State and Either . We can use those in place of functions like get and put . The second option is to create a general purpose way of turning any State or Either value into a Parser value. This is called lifting . You’ll see some examples of writing lifting functions later on in this chapter, but for now let’s stick with writing a couple of helper functions to handle the basic operations we’ll need to support in our parser:
| | parseError :: String -> Parser a |
| | parseError errMsg = Parser $ pure ( Left errMsg) |
| | |
| | parseGet :: Parser Text |
| | parseGet = Parser ( Right <$> State .get) |
| | |
| | parsePut :: Text -> Parser () |
| | parsePut newState = Parser $ Right <$> State .put newState |
With our new type class instances and our basic operations reimplemented, our parsing functions become much nicer to read. We don’t have to think about the fact that we have two nested computations, we can simply treat our Parser as a single cohesive type of computation that supports both errors and mutable state.
| | takeUntil :: ( Char -> Bool ) -> Parser Text |
| | takeUntil predicate = do |
| | oldState <- parseGet |
| | let (nextVal, rest) = Text .break predicate oldState |
| | parsePut rest |
| | pure nextVal |
| | |
| | optionally :: Parser () -> Parser () |
| | optionally originalParser = Parser $ do |
| | oldState <- State .get |
| | result <- runParser originalParser |
| | case result of |
| | Left _err -> State .put oldState |
| | _success -> pure () |
| | pure $ Right () |
| | |
| | word :: Parser Text |
| | word = do |
| | nextWord <- takeUntil isSpace |
| | when ( Text .null nextWord) $ |
| | parseError "unexpected end of input" |
| | optionally dropChar |
| | pure nextWord |
| | |
| | dropChar :: Parser () |
| | dropChar = do |
| | parseState <- parseGet |
| | case Text .uncons parseState of |
| | Nothing -> parseError "unexpected end of input" |
| | Just ( _ , rest) -> parsePut rest |
| | |
| | parseFullName :: Parser FullName |
| | parseFullName = FullName <$> word <*> word <*> word |
You’ll notice that one tradeoff we’ve had to make with our new error-aware parser is that our examples are a bit more complicated. We’ve had to create a new function, optionally , to handle running parsers that might fail. In this example, we’ve added this to account for the fact that the final word in our name won’t necessarily have a trailing character. We’ve also added some logic to word to account for the potentially empty input. Although these extra error checks are necessary for accurate parsing no matter what approach we’re using to parse text, as we build up a more sophisticated parser these types of checks will get easier to implement.