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-
[~ %]>
它一次消耗一行。
为什么它的行为不同?
最佳答案
当您在终端中运行程序时,它使用 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'
关于haskell - 为什么在终端中执行 getChar 与在 GHCi 中执行不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13004801/