(>>=) 的执行顺序不是我所期望的
我有一系列网络请求,每个请求都需要 10 秒以上。
为了让用户知道发生了什么,我提供更新:
main = do putStr "Downloading the first thing... "
{- Net request -}
putStrLn "DONE"
putStr "Downloading the second thing... "
{- Net request -}
putStrLn "DONE"
使用 GHCi 可以按预期工作,但是编译或使用 runghc,“下载”不会打印,直到“完成”为止。
我用 (>>=) 和 (>>) 重写了它,但我遇到了同样的问题。
这是怎么回事?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这里的问题不在于执行顺序。这些语句完全按照您期望的顺序执行。问题是,由于缓冲,您实际上并不能在结果发生时立即看到结果。
具体来说,终端 IO 默认情况下是行缓冲的。这意味着在打印换行符或刷新缓冲区之前,屏幕上不会出现任何输出。因此,您需要使用 < 刷新输出流执行
putStr
后code>hFlush或者您需要使用hSetBuffering
不使用行缓冲。The problem here isn't with the execution order. The statements execute in exactly the order you expect. The problem is that due to buffering, you don't actually see the results as soon as they happen.
Specifically terminal IO is line-buffered by default. This means that no output will appear on the screen until you print a newline or flush the buffer. So you need to either flush the´output stream using
hFlush
after executingputStr
or you need to change stdout's buffering mode usinghSetBuffering
to not use line buffering.