Haskell interaction()截断我的输出?

时间:2014-11-12 22:54:12

标签: haskell io functional-programming

我正在开发一个包含以下代码行的基本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) )

1 个答案:

答案 0 :(得分: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]