Search code examples
haskelltypesfunctional-programmingmonads

Can `guard` not guards in Haskell be used to specify a particular message for `Left`


Does the guard function from RIO-Prelude offer any way to decide the content of a message if it is failing an Either-Monad? such that e.g

somefun :: Either String Int
somefun =  do guard (4+2 == 8); return 2

would return Left someContent instead where the someContent is a string that is specified to the guard in some way.

I haven't been able to find any way according to the documentation, but in case it exists I would be happy to know about it, since guard could be a good way to avoid nested if-statements.


Solution

  • This sounds more like a job for when or unless:

    somefun :: Either String Int
    somefun = do
       unless (4+2 == 8) $ Left somecontent
       return 2
    

    I'd actually rather write when (4+2 /= 8) $ Left somecontent.