【问题标题】:Haskell interact() truncating my output?Haskell interact() 截断我的输出?
【发布时间】:2014-11-12 22:54:12
【问题描述】:

我正在开发一个包含这行代码的基本 Haskell 程序:

interact (unwords . (map pigLatin . words) )

但是,在将字符串数组传递给我的 pigLatin 函数后,再包装回一个字符串,它总是会截断我输入的最后一个单词。例如:

*HaskellPractice> getUserInput
this is broken
histay isway 

由于某种原因,它没有打印出来。 我在 Mac 上,所以在调用交互之前,我在 getUserInput 中声明了以下选项:

hSetBuffering stdin LineBuffering
hSetBuffering stdout NoBuffering

我猜这是一个我还没有完全理解的小细节。感谢您的任何输入/帮助! OSFTW 编辑:这是整个程序。

    import System.IO

pigLatin :: String -> String
pigLatin word = if ( (head word) `elem`['a', 'e', 'i', 'o', 'u'] )
    then (word ++ "way")
        else  (tail word) ++ [(head word)] ++ "ay"

getUserInput = do
    hSetBuffering stdin LineBuffering
    hSetBuffering stdout NoBuffering

    interact (unwords . (map pigLatin . words) )

【问题讨论】:

  • 你能发布一个完整的程序来复制这个问题吗?当您从 ghci 运行时,您是否在输入的末尾键入了 Control-d?
  • 感谢您的关注!我更新了OP。是的,我正在按下 control-d

标签: haskell io functional-programming


【解决方案1】:

这是我测试的程序:

import System.IO

pigLatin xs = "[" ++ xs ++ "]"

main = do
  hSetBuffering stdin LineBuffering
  hSetBuffering stdout NoBuffering
  interact (unwords . (map pigLatin . words) )

这是ghci 会话的样子:

*Main> :main
this is line1
[this] [is] this is line2
[line1] [this] [is] [line2]<stdin>: hGetBuffering: illegal operation (handle is closed)

我输入了:

this is line1
this is line2
(Control-d)

所以它不会截断输入 - 它只是在读取下一行(或遇到 EOF)之前不发出行中的最后一个单词。

如果你从 shell 运行它,你会得到你所期望的:

shell$ (echo this is line1; echo this is line2) | runhaskell  ./platin.hs

[this] [is] [line1] [this] [is] [line2]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-08
    • 1970-01-01
    • 1970-01-01
    • 2020-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多