我是Haskell的新手,一直试图更好地理解IO monad(在使用纯函数玩了一段时间之后)。Haskell中的自定义循环打印两次语句
我下面就以IO monad
之一演习正在一会儿功能的教程。他们没有显示一个例子,所以你不能检查你的答案。
这里是我的:
while :: IO Bool -> IO()
while action = do p <- action
if p then putStrLn "You win!" >> return()
else putStrLn "Nope. Try again!" >> while action
main = do putStrLn "Come and guess the letter!"
while (constAskForC)
where constAskForC = do c <- getChar
return $ c == 'c'
现在,我的问题是,如果你输入一个错误的字符(几乎是一个字,是不是“C”),然后串“不再试一次!”打印两次到StdOut。为什么是这样?这里的程序运行:
Come and guess the letter!
"Nope. Try again!"
"Nope. Try again!"
d
"Nope. Try again!"
"Nope. Try again!"
"Nope. Try again!"
"Nope. Try again!"
a
"Nope. Try again!"
"Nope. Try again!"
d
"Nope. Try again!"
"Nope. Try again!"
f
"Nope. Try again!"
"Nope. Try again!"
a
"Nope. Try again!"
"Nope. Try again!"
s
"Nope. Try again!"
"Nope. Try again!"
如果你只是按回车(输入没有字符),那么它只会打印一次。任何人都可以向我解释我做错了什么?
谢谢。
我最初的猜测是缓冲模式。导入'System.IO'后试试'hSetBuffering stdout LineBuffering',看看是否解决了你的问题。 – bheklilr
你输入一个字母并按下回车键。一封信是一个字符。Enter是另一个字符。这给出了两个字符,数它们;) –