Before we close out this chapter, let’s address one more ergonomic inconvenience that has cropped up a few times: dealing with parsers that might fail. When we were manually building the parsing functions inside of FilePackParser this wasn’t such a big deal, but as we’ve been able to build more and more of our code out of smaller parsers that we are composing, having to manually construct a parser with a Left value starts to get inconvenient. Worse, it ties us to a specific representation of our errors. In the future, if we wanted to refactor our parser to not use Either , we’d need to change every single error in our code base.
One option here would be to factor out the error handing into its own function:
| | parseError :: String -> FilePackParser a |
| | parseError errMsg = FilePackParser (const $ Left errMsg) |
This works well enough, but it’s specific to our particular parser. A better option is to re-use a well-known type class for monadic values that might fail: MonadFail . The MonadFail type class has a single definition:
| | class Monad m => MonadFail m where |
| | fail :: String -> m a |
Instances of MonadFail should obey the law:
| | fail a >>= b == fail a |
In other words, calling fail should end the computation at the first failure that we encounter. This is exactly the behavior we’ve already been using, and we can directly re-use parseError as the implementation of fail to create our own instance of MonadFail for FilePackParser :
| | instance MonadFail FilePackParser where |
| | fail errMsg = FilePackParser (const $ Left errMsg) |
Let’s use our new instance to make a small refactor to our Decode instance of FilePackImage :
| | instance Decode FilePackImage where |
| | decode = execParser $ do |
| | tag <- extractValue @ String |
| | case tag of |
| | "pbm" -> |
| | FilePackPBM |
| | <$> extractValue |
| | <*> extractValue |
| | <*> many extractValue |
| | "pgm" -> |
| | FilePackPGM |
| | <$> extractValue |
| | <*> extractValue |
| | <*> extractValue |
| | <*> many extractValue |
| | otherTag -> |
| | fail $ "unknown image type tag: " <> otherTag |
As you can see, having a MonadFail instance doesn’t make a huge difference to our code, but being able to use fail when a parser fails is a small ergonomic nicety for users of our library. Since MonadFail is common for monadic parsers, using it will make our parser feel consistent with many of the common parsers provided by various libraries in the Haskell ecosystem.