import Data.Char
main = do
c <- getChar
if not $ isUpper c
then do putChar $ toUpper c
main
else putChar '\n'
在GHCi中加载和执行:
λ> :l foo.hs
Ok, modules loaded: Main.
λ> main
ñÑsSjJ44aAtTR
λ>
这会消耗一个字符。
但在终端:
[~ %]> runhaskell foo.hs
utar,hkñm-Rjaer
UTAR,HKÑM-
[~ %]>
它会消耗一行。
为什么表现不同?
答案 0 :(得分:11)
当您在终端中运行程序时,默认情况下使用LineBuffering
,但在ghci
中,它会设置为NoBuffering
。你可以阅读它here。您必须从stdin
和stdout
中移除缓冲以获得类似的行为。
import Data.Char
import System.IO
main = do
hSetBuffering stdin NoBuffering
hSetBuffering stdout NoBuffering
foo
foo = do
c <- getChar
if not $ isUpper c
then do putChar $ toUpper c
foo
else putChar '\n'