Avoiding declaring nonsensical Error instance
I have a custom error type with various constructors, let's call it MyError:
data MyError = ConditionA String | ConditionB String | ConditionC String
The constructors categorise the type of error, and the strings provide
additional detail. I want to use my error type in the Either monad, for
example I want a function like
myFunction :: a -> Either MyError a
Inside myFunction, I want to use the maybeToEither function from
Data.Either.Utils in MissingH:
maybeToEither :: MonadError e m => e -> Maybe a -> m a
But ghc tells me that to do this, I have to make MyError and instance of
Error. This seems to come down to the fact that MonadError requires m to
be a monad, and that the monad instance for Either e requires Error e
because of fail:
instance (Error e) => Monad (Either e) where
return = Right
Left l >>= _ = Left l
Right r >>= k = k r
fail msg = Left (strMsg msg)
How then can I avoid making a non-sensical Error instance declaration for
MyError?
I noticed that the authors of Database.MongoDB.Query had the same problem
with their Failure datatype (which also has multiple constructors and
therefore no sensible Error instance), and their solution was to treat the
use of fail as an error:
instance Error Failure where strMsg = error
Is that my best option here?
No comments:
Post a Comment