15

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]

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

4

2 回答 2

25

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
于 2013-10-22T09:18:06.210 回答
11

stdin并且stdout是两个不需要任何连接的不同文件。以 Unix shell 命令为例grep

$ seq 1 100 | grep 2$ | less

seq 1 100将数字 1 到 100 打印到它stdoutgreps stdin|stdout一个命令的连接到另一个命令stdin的)。grep然后将与给定正则表达式匹配的行写入stdoutlesss stdin

强制stdout(或任何其他文件)写入使用hFlushfrom System.IO

 hFlush stdout
于 2013-10-22T18:45:31.477 回答