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

问题描述

我的一个朋友问我为什么要学习Haskell。为了演示哈斯克尔的力量,我编写了一个小程序,其中显示了一个素数列表:

pre $ code main = do
putStr输入要显示的素数的数量:
number< - fmap read getLine :: IO Int
print。以号码。过滤器isPrime $ [2 ..]

isPrime :: Integer - > Bool
isPrime n =不是。任何((== 0)。mod n)$ [2..floor。 sqrt。 fromInteger $ n]

程序按预期工作,保存了一个小异常。它会在输入用户输入号码后输出提示消息,从而产生如下输出:

  12 
输入要显示的素数的数量:[2,3,5,7,11,13,17,19,23,29,31,37]

为什么Haskell没有对IO操作进行正确排序?我在哪里出错?

解决方案

这看起来更像是一种缓冲而不是排序问题。你在哪个平台上?您尝试强制unbuffered输出?

  hSetBuffering标准输出NoBuffering  - 从System.IO 


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?

解决方案

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操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 21:49