【发布时间】:2014-01-09 16:33:32
【问题描述】:
我是 Haskell 的新手,一直在努力更好地理解 IO monad(在玩了一段时间的纯函数之后)。
我正在关注IO monad上的教程
其中一个练习是制作 while 函数。他们没有显示示例,因此您无法检查答案。
这是我的:
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' 的字符),那么字符串 "Nope. Try again!"被打印两次到 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,看看是否能解决您的问题。 -
您输入一个字母并按回车键。一个字母就是一个字符。 Enter 是另一个字符。这给出了两个字符,数一下;)