[Haskell-cafe] Why does the transformers/mtl 'Error' class exist?

Ryan Ingram ryani.spam at gmail.com
Thu Apr 15 23:18:05 EDT 2010


It's used in the implementation of "fail" for those monads.

class Monad m where
   ...
   fail :: String -> m a
   fail = error  -- default implementation

which is then used to desugar do-notation when pattern matching fails:

    do
        Left x <- something
        return x
=>
     something >>= \v -> case v of { Left x -> return x ; _ -> fail
"Pattern match failure ..." }

You can argue about whether "fail" belongs in Monad (and many people
have), but that's why it is how it is.

  -- ryan

On Thu, Apr 15, 2010 at 7:18 PM, John Millikin <jmillikin at gmail.com> wrote:
> Both the transformers[1] and mtl[2] define a class named 'Error', for
> use with MonadError and ErrorT. This class is required for the
> instance of Monad (and therefore MonadTrans, MonadIO, etc). However, I
> can't figure out why this class exists. Its presence means that
> instead of something like:
>
> -------------------------------------
> data NameError = ErrorFoo | ErrorBar
> validateName :: Monad m => Text -> m (Either Error Text)
> validateName x = runErrorT $ do
>    when (some condition) $ throwError ErrorFoo
>    when (other condition) $ throwError ErrorBar
>    return x
> -------------------------------------
>
> I have to define this, which is more verbose, no more useful, and adds
> a "fake" class to the Haddock docs (with a warning not to use it):
> -------------------------------------
> data Error = ErrorFoo | ErrorBar
>
> instance Error NameError where
>    strMsg = error
>
> -- validateName ...
> -------------------------------------
>
> Is there any good reason why the 'Error' class can't just be removed?
>
> [1] http://hackage.haskell.org/packages/archive/transformers/0.2.0.0/doc/html/Control-Monad-Trans-Error.html
> [2] http://hackage.haskell.org/packages/archive/mtl/1.1.0.2/doc/html/Control-Monad-Error-Class.html
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
>


More information about the Haskell-Cafe mailing list