为什么在终端中执行getChar与在GHCi中执行它不同?

时间:2012-10-22 03:57:50

标签: haskell

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-
[~ %]>

它会消耗一行。

为什么表现不同?

1 个答案:

答案 0 :(得分:11)

当您在终端中运行程序时,默认情况下使用LineBuffering,但在ghci中,它会设置为NoBuffering。你可以阅读它here。您必须从stdinstdout中移除缓冲以获得类似的行为。

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'