Feeding a monadic expression into unless or when

haskell, monads

Solution

I could define a helper function:

unlessM :: Monad m => m Bool -> m () -> m ()
unlessM b s = b >>= (\t -> unless t s)

example3 = unlessM (doesFileExist "wombat.txt") $ 
  putStrLn "Guess I should create the file, huh?"

It seems like `unlessM` would be very useful. But the fact that I don't see anything like `unlessM` (or with that type signature) on Hackage makes me think that there's some better way to handle this situation, one that I haven't discovered yet. What do the cool kids do?

Problem

I often find myself writing code that looks like this: ``` import System.Directory (doesFileExist) import Control.Monad (unless) example = do fileExists <- doesFileExist "wombat.txt" unless fileExists $ putStrLn "Guess I should create the file, huh?" ``` Perhaps a better way is: ``` example2 = doesFileExist "wombat.txt" >>= (\b -> unless b $ putStrLn "Guess I should create the file, huh?") ``` What's the best approach here?

Original source