【问题标题】:Haskell IO with interact and map具有交互和映射的 Haskell IO
【发布时间】:2011-05-31 16:16:04
【问题描述】:

我正在尝试使用interact 函数和map 生成交互式Haskell 程序。

这是我在 ghci 中得到的(据我所知,这是所有教程解释 interact 用法的方式——除了结果)。

*Module> interact $ unlines . map (++ "!") . lines
tteesstt
!

请注意,实际发生的情况是我输入的每个字符都会立即重复,并且在我按下 Return 后会出现感叹号。然而,我期待这个:

*Module> interact $ unlines . map (++ "!") . lines
test
test!

如果我使用相同的程序结构,但使用filter 而不是map,它会完美运行。

【问题讨论】:

    标签: haskell map io buffering


    【解决方案1】:

    问题在于 ghci 将缓冲模式更改为按字符。也就是说,程序一有代码就开始处理代码。如果你将此行写入一个名为foo.hs的文件中

    main = interact $ unlines . map (++ "!") . lines
    

    并使用runhaskell foo.hs 运行它,您会看到它按预期工作,因为 Haskell 默认使用行缓冲。

    【讨论】:

    • 谢谢,这是完全正确的。可以通过执行import IO 然后hSetBuffering stdout LineBuffering 将其设置为行缓冲。
    【解决方案2】:

    正如 FUZxxl 所说,it's a buffering issue

    要更改 GHCi 中的缓冲样式,请使用 hSetBuffering

    Prelude> :m +System.IO
    Prelude System.IO> hSetBuffering stdout LineBuffering 
    Prelude System.IO> interact $ unlines . map (++"!") . lines
    hello
    hello!
    ^CInterrupted.
    Prelude System.IO> 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-19
      • 1970-01-01
      相关资源
      最近更新 更多