(>>=) 的执行顺序不是我所期望的

发布于 2024-12-19 04:18:25 字数 420 浏览 3 评论 0 原文

我有一系列网络请求,每个请求都需要 10 秒以上。
为了让用户知道发生了什么,我提供更新:

main = do putStr "Downloading the first thing... "
          {- Net request -}
          putStrLn "DONE"
          putStr "Downloading the second thing... "
          {- Net request -}
          putStrLn "DONE"

使用 GHCi 可以按预期工作,但是编译或使用 runghc,“下载”不会打印,直到“完成”为止。

我用 (>>=) 和 (>>) 重写了它,但我遇到了同样的问题。

这是怎么回事?

I've got a series of network requests, that each take >10 seconds.
So that the user knows what's happening, I give updates:

main = do putStr "Downloading the first thing... "
          {- Net request -}
          putStrLn "DONE"
          putStr "Downloading the second thing... "
          {- Net request -}
          putStrLn "DONE"

With GHCi this works as expected, but compiled or with runghc, "Downloading" doesn't print till "DONE" does.

I've rewritten it with (>>=) and (>>), but I get the same problem.

What's going on?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

北方。的韩爷 2024-12-26 04:18:25

这里的问题不在于执行顺序。这些语句完全按照您期望的顺序执行。问题是,由于缓冲,您实际上并不能在结果发生时立即看到结果。

具体来说,终端 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 executing putStr or you need to change stdout's buffering mode using hSetBuffering to not use line buffering.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文