如何在Haskell中组合monad?

时间:2009-07-14 16:47:06

标签: haskell functional-programming monads monad-transformers

特别是,我需要能够将CGI monad与IO monad结合起来,但是如何将IO monad与Maybe monad相结合的示例可能会更好......

3 个答案:

答案 0 :(得分:21)

我假设你想使用Maybe monad提前终止(比如C中的breakreturn)。

在这种情况下,您应该使用MaybeT包中的MaybeTcabal install MaybeT)。

main = do
  runMaybeT . forever $ do
    liftIO $ putStrLn "I won't stop until you type pretty please"
    line <- liftIO getLine
    when ("pretty please" == line) mzero
  return ()

MaybeT是monad的monad变换器版本。

Monad变形金刚“向其他monad添加功能”。

答案 1 :(得分:17)

您并未确切地说明要如何合并IOMaybe,但我认为您有许多函数会返回IO (Maybe a),您希望轻松合并它们。基本上,您希望将IO (Maybe a)视为一个单独的类型,并使用它自己的Monad实例:

newtype IOMaybe a = IOM (IO (Maybe a))

-- "unpack" a value of the new type
runIOMaybe :: IOMaybe a -> IO (Maybe a)
runIOMaybe (IOM a) = a

instance Monad IOMaybe where
   -- bind operator
   (IOM ioa) >>= f = IOM $ do
      a <- ioa
      case a of
         Nothing -> return Nothing
         Just v  -> runIOMaybe (f v)

   -- return
   return a = IOM (return (Just a))

-- maybe also some convenience functions
returnIO :: IO a -> IOMaybe a
returnIO ioa = IOM $ do
   v <- ioa
   return (Just v)

returnMaybe :: Maybe a -> IOMaybe a
returnMaybe ma = IOM (return ma)

使用此功能,您可以使用do - 符号来合并返回IO (Maybe a)IO aMaybe a的函数:

f1 :: Int -> IO (Maybe Int)
f1 0 = return Nothing
f1 a = return (Just a)

main = runIOMaybe $ do
   returnIO $ putStrLn "Hello"
   a <- returnMaybe $ Just 2
   IOM $ f1 a
   return ()

一般来说,组合和修改像这样的monad的东西叫做monad transformer,而GHC附带的package包括monad变换器用于常见情况。如果此monad变换器库中有适合您的场景的内容取决于您希望如何组合Maybe和IO。

答案 2 :(得分:0)

你想在什么意义上结合monad?

f :: Int -> IO (Maybe Int)
f x = do
    putStrLn "Hello world!"
    return $ if x == 0 then Nothing else Just x

可以评估为:

[1 of 1] Compiling Main             ( maybe-io.hs, interpreted )
Ok, modules loaded: Main.
*Main> f 0
Hello world!
Nothing
*Main> f 3
Hello world!
Just 3