>>> fromMaybe "" (Just "Hello, World!") "Hello, World!"
>>> fromMaybe "" Nothing ""Read an integer from a string using readMaybe. If we fail to parse an integer, we want to return 0 by default:
>>> import Text.Read ( readMaybe ) >>> fromMaybe 0 (readMaybe "5") 5 >>> fromMaybe 0 (readMaybe "") 0
>>> let justVal = Just True :: Maybe Bool >>> fromMaybeExceptT 5 justVal :: ExceptT Int Identity Bool ExceptT (Identity (Right True))If the Maybe is Nothing, then use the default value as the error value:
>>> let nothingVal = Nothing :: Maybe Bool >>> fromMaybeExceptT 5 nothingVal :: ExceptT Int Identity Bool ExceptT (Identity (Left 5))
fromMaybeM nothingAction === maybe nothingAction pure
>>> fromMaybeM [] $ Just 5 [5] >>> fromMaybeM [] Nothing []
>>> let identityNothing = Identity Nothing :: Identity (Maybe Bool) >>> fromMaybeMExceptT 5 identityNothing :: ExceptT Int Identity Bool ExceptT (Identity (Left 5))
>>> fromMaybeMM [] [Just 6, Just 5] [6,5] >>> fromMaybeMM [] [Just 6, Nothing, Just 7] [6,7]NOTE: I don't particularly like the name of this function. If you have a suggestion for a better name, please submit a PR or issue.
fromMaybeM_ nothingAction === maybe nothingAction (const $ pure mempty)
>>> fromMaybeM_ (putStrLn "hello" >> pure "bye") $ Just 5 "" >>> fromMaybeM_ (putStrLn "hello" >> pure "bye") Nothing hello "bye"This can be convenient when you want to run some sort of logging function whenever a Maybe is Nothing. If you imagine the logging function is IO '()', then the effective type of fromMaybeM_ becomes fromMaybeM_ :: IO '()' -> Maybe a -> IO '()', because '()' has a Monoid instance, and IO, has an Applicative instance.
>>> fromMaybeM_ (putStrLn "hello") Nothing hello
>>> fromMaybeOrM (Just 5) [] [5]This can be nice to use as an error handler.
>>> fromMaybeOrM (Just 5) $ putStrLn "some error occurred" >> undefined 5 >>> fromMaybeOrM (Nothing) $ putStrLn "some error occurred" >> undefined some error occurred ...