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:
- Maybe ignores the message and returns Nothing. section 12.1.7
- IO throws an exception containing the failure message. section 14.3.3
- Parser can encode failure as Left String. section 14.3.3
