Haskell有'when'和'excel'的组合吗?
我正在开发一个TCP客户端,它从流中获取特定种类的消息,并发现我自己使用了大量的除非和何时表达式。例如:Haskell有'when'和'excel'的组合吗?,haskell,monads,Haskell,Monads,我正在开发一个TCP客户端,它从流中获取特定种类的消息,并发现我自己使用了大量的除非和何时表达式。例如: hunt :: Socket -> ThreadId -> IO () hunt conn t = do threadDelay 1000000 msg <- recv conn 1024 unless (C.isInfixOf "1b14010
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
,需要在/时使用,除非再次使用。那么,Haskell在
/时是否有的组合,除非
?如果没有,那么对于我的案例,什么是更好的方法呢?如果。。。然后。。。否则
比如说,
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
waitfor::ByteString->Socket->t->(ByteString->Socket->t->IO())->IO()
等待str conn tid f=do
线程延迟1000000
msg感谢您的回复,但仍然无法将helper函数应用于其他函数,如hunt'?如果您包含hunt'
的代码,可能有人可以帮助您找到一个同时适用于这两种功能的帮助器。为什么您不能在if
表达式中使用hunt'
。@t。您是否可以给出一个具体的示例(或事物)你试图做的是不起作用的模式你的模式是foo=in do{..;如果某个东西然后foo-else..}
。这就是你应该抽象成自己函数的模式。我不确定我是否理解…为什么你不能使用waitfor
?你不能将hunt'
写成hunt'idx-conn=waitfor吗“0300aa0801”康涅狄格州t$do{…您原始狩猎的do块在这里…}
?你好,David Young,您的答案适用于我的案例。我可以修改等待
,并使用您建议的方式。谢谢:)
main = do
...
tid <- myThreadId
conn <- joinWorld u
waitfor "1b14010102" conn tid 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 :: 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