我正在开发一个TCP客户端,它从流中获取指定类型的消息,除了和表达式之外,我发现自己经常使用很多.例如:
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
Run Code Online (Sandbox Code Playgroud)
我试图建立一个帮手,如:
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
Run Code Online (Sandbox Code Playgroud)
然后我可以重新使用帮助器:
main = do
...
tid <- myThreadId
conn <- joinWorld u
waitfor "1b14010102" conn tid hunt.
Run Code Online (Sandbox Code Playgroud)
但如果我有另一个功能(它需要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
Run Code Online (Sandbox Code Playgroud)
然后我不能使用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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
205 次 |
| 最近记录: |