haskell – 在IO中提取Maybe值
給出以下內容:
> (liftM2 fromMaybe) (ioError $userError "OOPS") (return $Just "ok")
ghci給我
*** Exception: user error (OOPS)
當然,從Mayay可以正常工作:
> (liftM2 fromMaybe) (return $"not me") (return $Just "ok") "ok"
但是,IO操作似乎正在執行,然後被丟棄:
> (liftM2 fromMaybe) (putStrLn "computing.." >> "discarded") (return $Just "ok") computing.. "ok"
為什麼會發生這種情況?有沒有辦法使IO monad lazier?
具體來說,給定值:: IO(也許a)一個(乾淨,簡潔)的方式
result <- (liftM2 fromMaybe) err value
並解壓縮結果或相應地引發IOError?
test :: IO (Maybe a) -> IO a test = (>>= maybe (ioError $userError "oops") return)
http://stackoverflow.com/questions/8540999/extracting-a-maybe-value-in-io