haskell - 有没有办法在 if 语句中使用 IO Bool 而无需绑定(bind)到 haskell 中的名称?

标签 haskell monads

如果我有一个返回 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/

相关文章:

用于过滤任一输入列表的 Scala 多态函数

haskell - 使用 LLVM/Haskell 的 CodeGenFunction/CodeGenModule 的类型问题

haskell - Haskell 平台 2010.2.0.0 Cabal 中出现错误

haskell - 如何对惰性列表进行一次评估?

haskell - Repa 2 和 3 API 之间的主要区别是什么?

haskell - monads 如何让我的工作更轻松?给我看一段很酷的代码

haskell - 使用 System.Random 中的 mkStdGen 生成随机 bool 值

haskell - 是否有更深层次的类型理论原因 GHC 无法推断出这种类型?

scala - 结合Scala选项[Iterable[_]]

haskell - Cont 的 monad 实例有什么用?