haskell - Haskell 是否有 `when` 和 `unless` 的组合?

标签 haskell monads

我正在开发一个 TCP 客户端,它从流中获取指定种类的消息,并且发现我自己使用了很多 unless 和 when 表达式。例如:

hunt :: Socket -> ThreadId -> IO ()                               
hunt conn t = do threadDelay 1000000
                 msg <- recv conn 1024
                 unless (C.isInfixOf "1b14010102" $ encode msg) $ hunt conn t
                 when (C.isInfixOf "1b14010102" $ encode msg) $ do
                     threadDelay 7000000
                     sendAll conn $ goHunt
                     msg <- recv conn 1024
                     threadDelay 3000000
                     close conn
                     killThread t

我正在尝试构建一个像这样的助手:

waitfor :: ByteString -> Socket -> t -> (ByteString -> Socket -> t -> IO ()) -> IO ()
waitfor str conn tid f = do 
    threadDelay 1000000
    msg <- recv conn 1024
    let m = C.isInfixOf str msg
    unless m $ waitfor str conn tid f
    when m $ f msg conn tid

然后我可以重新使用助手:

main = do
    ...
    tid <- myThreadId
    conn <- joinWorld u
    waitfor "1b14010102" conn tid hunt.

但是如果我有另一个函数(它需要 3 个参数,不像 hunt)

hunt' :: ByteString -> Socket -> ThreadId -> IO ()
hunt' idx conn t = do threadDelay 1000000
                      msg <- recv conn 1024
                      unless (C.isInfixOf "0300aa0801" $ encode msg) $ hunt' conn t
                      when (C.isInfixOf "0300aa0801" $ encode msg) $ do
                          threadDelay 1000000
                          sendAll conn $ goHunt' idx
                          threadDelay 3000000
                          close conn
                          killThread t

那我就不能用waitfor了,需要再用when/unless。那么,Haskell 是否有 when/unless 的组合?如果不是,那么对我的情况来说更好的方法是什么?

最佳答案

您可以为此使用 if ... then ... else

例如,

waitfor :: ByteString -> Socket -> t -> (ByteString -> Socket -> t -> IO ()) -> IO ()
waitfor str conn tid f = do 
    threadDelay 1000000
    msg <- recv conn 1024
    if C.isInfixOf str msg
    then waitfor str conn tid f
    else f msg conn tid

关于haskell - Haskell 是否有 `when` 和 `unless` 的组合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45696542/

相关文章:

haskell - 没有 monad 转换器的 monad 的显式示例是什么?

haskell - 更喜欢 Reader monad 而不是直接将环境作为参数传递

haskell - 是否有像 `>>` 这样的标准函数,但返回第一个操作数的结果?

scala - State monad 在具有可变(本地)变量的语言(例如 Scala)中是否需要/有用?

haskell - 这个 Haskell kata 解决方案可以变得更惯用吗?

java - 为什么不能所有 Functor 都是 Monad?

haskell - Haskell RNG 和状态

haskell - 'Either e` 包中 `Failure` 的 "failure"实例存在问题

haskell - Haskell 中的除法错误

haskell - 动态编程算法如何在惯用的 Haskell 中实现?