鉴于以下情况:
> (liftM2 fromMaybe) (ioError $ userError "OOPS") (return $ Just "ok")
ghci 给我
*** Exception: user error (OOPS)
当然,fromMaybe 工作正常:
> (liftM2 fromMaybe) (return $ "not me") (return $ Just "ok")
"ok"
但是好像IO操作正在进行然后被丢弃:
> (liftM2 fromMaybe) (putStrLn "computing.." >> "discarded") (return $ Just "ok")
computing..
"ok"
为什么会发生这种情况?有没有办法让 IO monad 变得更懒?
具体来说,给定value::IO(也许是a)
什么是(干净、简洁)的表达方式
result <- (liftM2 fromMaybe) err value
并让它解压结果或相应地抛出 IOError 吗?
最佳答案
我不知道让 IO
更懒惰是正确的方向。您似乎想做的是首先找到“也许”,然后消除它。这可以用多种方式编写,这是一种选择:
test :: IO (Maybe a) -> IO a
test = (>>= maybe (ioError $ userError "oops") return)
关于haskell - 提取 IO 中的 Maybe 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8540999/