Home > other >  Haskell - How can I use Maybe in IO function
Haskell - How can I use Maybe in IO function

Time:09-22

main ::  IO ()
main = do
    result <- function_returns_io_maybe -- type of result is Maybe x
    -- if result maybe is Just, run function that return IO() with result, else do not run function.

How can I use Maybe in IO function?

CodePudding user response:

You can write any expression within a do block, as long as the expression has the correct monadic type for that block. In particular, you can do case analysis:

main = do
  result <- something
  case result of
    Just r -> somethingElse r
    Nothing -> return ()

(where something :: IO (Maybe X); somethingElse :: X -> IO ())

Personally, I’d write that with a lambda case and a bind:

{-# LANGUAGE LambdaCase #-}

main = something >>= \case
  Just r -> somethingElse r
  Nothing -> return ()

Case analysis on a Maybe is more succinctly written with the maybe combinator:

main = maybe somethingElse (return ()) =<< something

And Control.Monad.Extra.whenJustM captures this entire sort of operation:

import Control.Monad.Extra (whenJustM)

main = whenJustM something somethingElse
  • Related