鉴于以下情况:
> (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 (Maybe a)
到什么是(干净,简洁)的表达方式
result <- (liftM2 fromMaybe) err value
并让它解包结果或相应地抛出一个 IOError ?