我试图使用interact函数,但是以下代码出现了问题:
main::IO()
main = interact test
test :: String -> String
test [] = show 0
test a = show 3
我正在使用EclipseFP,输入一个值后出现了错误。尝试再次运行主程序,会导致以下错误:
*** Exception: <stdin>: hGetContents: illegal operation (handle is closed)
我不确定为什么这不起作用,测试类型是String -> String,显示为Show a => a -> String,因此它似乎应该是interact的有效输入。
编辑/更新:
我尝试了以下方法,它可以正常工作。使用unlines和lines如何使interact按预期工作?
main::IO()
main = interact respondPalindromes
respondPalindromes :: String -> String
respondPalindromes =
unlines .
map (\xs -> if isPal xs then "palindrome" else "not a palindrome") .
lines
isPal :: String -> Bool
isPal xs = xs == reverse xs
:load
、:reload
或:set +r
均无效。你有什么其他想法吗?我不想在每次执行getContents >>= print
后都需要重新启动 ghci。 - vikingsteve