liveBook · Manning

MonadFail

As explained in Learn Haskell by Example

Control.Monad.Fail is a Haskell library module defining the MonadFail type class and related functionality.

MonadFail gives a monadic computation an explicit failure operation, allowing pattern matches inside monadic code to fail instead of requiring every pattern to succeed. section 12.1.7 section 12.3

class Monad m => MonadFail m where
  fail :: String -> m a

The class accepts an error message and returns a monadic value of any result type. section 12.1.7

Failing safely with mhead

A monadic list-head function requires MonadFail because the pattern (x : _) can fail. With Maybe, a nonempty list produces Just 1 and an empty list produces Nothing; with IO, the empty case raises an exception. section 12.1.7

Using failure in a parser

A Parser instance can turn fail into a Left error. The integer parser uses fail when readMaybe cannot convert its collected text into an integer, preserving a useful error message. section 12.1.7

Failure behavior depends on the monad:

How Learn Haskell by Example covers it

How deep it goes
Explains the class signature, failing patterns, and instances for Maybe, IO, and Parser, while deferring exception handling.
Examples
Uses mhead, Maybe and IO evaluations, a Parser instance, and integer conversion errors.
What it assumes
Assumes monads and pattern matching, while demonstrating failure behavior through Maybe, IO, and Parser.
What you can do after
Builds MonadFail instances and applies fail to represent parser errors or trigger monad-specific failure behavior.
How it connects
Connects monads with pattern matching, parsing, Maybe, IO, Either, exceptions, Alternative, and MonadPlus.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Haskell by Example. The section links point to the parts of the book it draws on.