Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use or Abuse of the Error Monad Transformer

Tags:

haskell

styles

Background

I am working with a monad built of a stack of transformers one of which is ErrorT. My monad therefore implements the MonadError class and throwError is a valid statement. I want to throw and error only when a certain condition is met. I am inclined to do the following:

if badCondition
  then throwError "You did a bad, bad thing..."
  else return ()
doGoodThings
[...]

In looking at this I think I can even generalize it to the following:

throwErrorWhen :: (MonadError e m) => Bool -> e -> m ()
throeErrorWhen cond err = if cond then throwError e else return ()

In fact this seems so obvious that I was surprised that it was not the MonadError Library.

Question:

Is there a better/more correct way to raise an error only is some condition is met?

like image 833
John F. Miller Avatar asked Dec 13 '22 01:12

John F. Miller


1 Answers

There's the when function in Control.Monad that evaluates its 2nd argument if the Boolean is true:

when :: Monad m => Bool -> m () -> m ()

So you get,

throwErrorWhen cond e = when cond (throwError e)  
like image 70
Peter Avatar answered Dec 28 '22 23:12

Peter