为什么 Haskell 不能正确排序这些 IO 操作? [英] Why doesn't Haskell sequence these IO actions properly?

查看:17
本文介绍了为什么 Haskell 不能正确排序这些 IO 操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的一个朋友问我为什么要学习 Haskell.为了展示 Haskell 的强大功能,我编写了一个显示质数列表的小程序:

A friend of mine asked me why was I learning Haskell. To demonstrate the power of Haskell I wrote a small program which displayed a list of prime numbers:

main = do
    putStr "Enter the number of prime numbers to display: "
    number <- fmap read getLine :: IO Int
    print . take number . filter isPrime $ [2..]

isPrime :: Integer -> Bool
isPrime n = not . any ((== 0) . mod n) $ [2..floor . sqrt . fromInteger $ n]

该程序按预期工作,但存在轻微异常.它在从用户那里获取输入号码后打印提示消息,结果如下:

The program works as expected save a minor anomaly. It prints the prompt message after taking an input number from the user resulting in an output like:

12
Enter the number of prime numbers to display: [2,3,5,7,11,13,17,19,23,29,31,37]

为什么 Haskell 没有正确排序 IO 操作?我哪里出错了?

Why is Haskell not sequencing the IO actions correctly? Where am I going wrong?

推荐答案

这看起来更像是一个缓冲而不是排序问题.你在什么平台?您是否尝试过强制无缓冲输出?

This looks more like a buffering than a sequencing problem. What platform are you on? Have you tried forcing unbuffered output?

hSetBuffering stdout NoBuffering -- from System.IO

这篇关于为什么 Haskell 不能正确排序这些 IO 操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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