(>> =)的执行顺序不符合我的预期 [英] Execution order with (>>=) not what I expected

查看:86
本文介绍了(>> =)的执行顺序不符合我的预期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到了一系列网络请求,每个请求都需要超过10秒。

为了让用户知道发生了什么,我给出了更新:


$ b $
{ - 网络请求 - }
putStrLn完成
putStr下载第一件东西b

  main =下载第二件事......
{ - 网络请求 - }
putStrLnDONE

GHCi的工作方式和预期一样,但是编译或者使用runghc,Downloading直到DONE才会打印。

我改写了它与(>> =)和(>>),但我得到同样的问题。



发生了什么?

解决方案

这里的问题与执行顺序不同。这些语句按您期望的顺序执行。问题是,由于缓冲,你实际上没有看到结果一旦发生。



具体来说,终端IO默认是行缓冲的。这意味着在打印换行符或清空缓冲区之前,屏幕上不会显示任何输出。因此,您需要使用 <执行 putStr 后执行code> hFlush ,或者您需要使用 hSetBuffering 不是使用行缓冲。


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?

解决方案

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.

这篇关于(&gt;&gt; =)的执行顺序不符合我的预期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆