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

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

它一次消耗一行。

为什么它的行为不同?

最佳答案

当您在终端中运行程序时,它使用 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/

相关文章:

haskell - 导入数据构造函数而不导入类型

algorithm - 列表处理的 Haskell 优化因惰性评估而受阻

haskell - 使用自定义比较器函数压缩两个列表的标准方法

haskell - 我怎么能提前知道 cabal 将生成的可执行文件放在哪里?

list - 如何更新 Haskell 列表中的特定元组?

haskell - 仅在某些情况下在 GHC 解释器中执行 : concat <some list> ! 时才会发生空间泄漏! n

string - 在 Haskell 中生成大量文本的有效方法

haskell - 解构 GADT : Where am I losing the context?

haskell - 带有 HOAS 的复制器解释器

haskell - 如何定义像1这样的对象?