如果我有一个返回 IO Bool
的函数(特别是 atomically
),有没有办法直接在 if
中使用返回值?声明,没有约束力?
所以目前我有
ok <- atomically $ do
...
if (ok) then do
...
else do
...
有没有可能把它写成类似的东西
if (*some_operator_here* atomically $ do
...) then do
...
else do
...
我希望有一种方法可以使用
<-
之类的东西匿名,即 if (<- atomically ...)
但到目前为止还没有这样的运气。同样在 getLine 上,是否可以编写类似的东西
if ((*operator* getLine) == "1234") then do ...
相关附录——
(<-)
的类型是什么? ?我无法让它出现在 ghci 中。我假设它是 m a -> a
,但这意味着它可以在单子(monad)之外使用来逃避单子(monad),这是不安全的,对吧?是 (<-)
根本不是一个功能?
最佳答案
您可以使用 ifM
来自 Control.Conditional
如果这符合您的目的,并且编写类似的功能甚至不难。
只是给你举个例子
import Control.Conditional
import Control.Monad
(==:) :: ( Eq a,Monad m) => m a -> m a -> m Bool
(==:) = liftM2 (==)
main = ifM (getLine ==: getLine) (print "hit") (print "miss")
我认为有一些方法可以使用可重新绑定(bind)的语法扩展,甚至可以使用
if c then e1 else e2
类似于 ifM
的语法但这不值得尝试。
关于haskell - 有没有办法在 if 语句中使用 IO Bool 而无需绑定(bind)到 haskell 中的名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16952335/