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

hel*_*elq 8 haskell

import Data.Char

main = do 
    c <- getChar
    if not $ isUpper c
        then do putChar $ toUpper c
                main
        else putChar '\n'
Run Code Online (Sandbox Code Playgroud)

在GHCi中加载和执行:

?> :l foo.hs
Ok, modules loaded: Main.
?> main
ñÑsSjJ44aAtTR
?>
Run Code Online (Sandbox Code Playgroud)

这会消耗一个字符.

但在终端:

[~ %]> runhaskell foo.hs
utar,hkñm-Rjaer 
UTAR,HKÑM-
[~ %]>
Run Code Online (Sandbox Code Playgroud)

它一次消耗一行.

为什么它的表现不同?

Sat*_*vik 12

当您在终端中运行程序时,它LineBuffering默认使用,但在ghci其中设置为NoBuffering.你可以在这里阅读它.您将不得不从中删除缓冲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'
Run Code Online (Sandbox Code Playgroud)