Haskell interact()截断了我的输出?

3

我正在开发一个基本的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) )

2
你能否发布一个完整的程序来复制这个问题吗?当你从ghci运行它时,你是否在输入的末尾键入Control-d? - ErikR
谢谢您关注这个问题!我已经更新了原始帖子。是的,我正在按下控制键-d。 - OpenSrcFTW
1个回答

2

以下是我测试过的程序:

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]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接