[英]Haskell sequence of IO actions processing with filtration their results in realtime+perfoming some IO actions in certain moments
[英]Why doesn't Haskell sequence these IO actions properly?
我的一個朋友問我為什么要學習 Haskell。 為了展示 Haskell 的強大功能,我編寫了一個顯示素數列表的小程序:
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]
該程序按預期工作,但存在輕微異常。 它在從用戶那里獲取輸入號碼后打印提示消息,結果如下:
12
Enter the number of prime numbers to display: [2,3,5,7,11,13,17,19,23,29,31,37]
為什么 Haskell 沒有正確排序 IO 操作? 我哪里錯了?
這看起來更像是緩沖而不是排序問題。 你在什么平台? 您是否嘗試過強制無緩沖輸出?
hSetBuffering stdout NoBuffering -- from System.IO
stdin
和stdout
是兩個不同的文件,不需要任何連接。 以 Unix shell 命令grep
為例:
$ seq 1 100 | grep 2$ | less
seq 1 100
將數字 1 到seq 1 100
打印到它的stdout
,即grep
s stdin
( |
將一個命令的stdout
連接到另一個命令的stdin
)。 然后grep
將與給定正則表達式匹配的行寫入其stdout
,它less
s stdin
。
要強制寫入stdout
(或任何其他文件),請使用System.IO
hFlush
:
hFlush stdout
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.