我想阅读一系列输入并将其转换为[String]
。怎么可能?
例如:
> Enter a string: foo
> Enter a string: bar
> Enter a string: !
> The strings you've entered are ["foo", "bar"].
在这种情况下,!
是确定输入结束的控制字符。
答案 0 :(得分:4)
readLines :: String -> IO [String]
readLines msg = do
putStr msg
line <- getLine
if line == "!"
then return []
else
do
lines <- readLines msg
return (line:lines)
使用示例
Prelude> readLines "Enter data: "
Enter data: foo
Enter data: oof
Enter data: fof
Enter data: ofo
Enter data: !
["foo","oof","fof","ofo"]
Prelude>
或者
Prelude> readLines "Enter data: " >>= (\strings -> putStrLn ("The strings you've entered are " ++ show strings))
Enter data: fofo
Enter data: ofof
Enter data: !
The strings you've entered are ["fofo","ofof"]
Prelude>
或者
main = do
strings <- readLines "Enter data: "
putStrLn $ "The strings you've entered are " ++ show strings
答案 1 :(得分:3)
这是一个类似的例子,来自Real World Haskell, chapter 7,这对你来说是一个很好的资源。
main = do
putStrLn "Greetings! What is your name?"
inpStr <- getLine
putStrLn $ "Welcome to Haskell, " ++ inpStr ++ "!"
既然您已经知道如何读取字符串并打印它们,那么您唯一的挑战就是创建一个包含两个字符串的数组并将其打印出来。提示:尝试show
命令。
如果您仍需要帮助,请告诉我们您尝试过的内容,并提供您收到的任何错误消息。