haskell - 提取 IO 中的 Maybe 值

标签 haskell io monads option-type

鉴于以下情况:

> (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/

相关文章:

algorithm - 尝试为 Haskell 中的函数创建高效算法

c - 为什么格式化输入输出需要提供变量?

c - 如何使用C中的系统调用逐行读取

list - 如何使用 bind (>>=) 实现一个函数

file-io - 一元文件 I/O

haskell - 避免显式传递查找表

list - 使用 'nub' 函数需要什么?

haskell - “惯用的” haskell 型不等式

haskell - 何时在 Haskell 中使用多参数类型类?

python - 尝试从包含奇怪字符的文件中读取某些文本。 (Python)