为什么我的角色echo等待换行符,回显整个字符串而不是char-for-char

时间:2013-03-15 15:14:45

标签: haskell

我期望的一小段代码因为我正在使用char get / put方法应该响应每个输入字符,但事实并非如此;相反,它等待换行,然后运行整个字符串,这对我来说并不完全有意义......

我做错了什么?如何让它对每个输入字符做出反应?

main = repeatUntilExit stdin stdout putChar ""

repeatUntilExit :: Handle -> Handle -> (Char -> IO ()) -> [Char] -> IO ()
repeatUntilExit hIn hOut f "exit\n" = hPutStrLn hOut "bye\n"
repeatUntilExit hIn hOut f x = hGetChar hIn >>= \c -> f c >> repeatUntilExit hIn hOut f (appendToLastFive c)
  where appendToLastFive a = (reverse . (:)a . take 4 . reverse) x

结果是:

C:\temp>echo.exe
an entire line of text
an entire line of text
exit
exit
bye

C:\temp>

1 个答案:

答案 0 :(得分:5)

这是一个buffering问题。

import System.IO

hSetBuffering stdin NoBuffering

然而,这不适用于Windows,仍然是一个未经修复的问题here