-1

我想读取一系列输入并将它们转换为[String]. 这怎么可能?

例如:

> Enter a string: foo
> Enter a string: bar
> Enter a string: !
> The strings you've entered are ["foo", "bar"].

在这种情况下,!是决定输入结束的控制字符。

4

2 回答 2

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
于 2013-06-11T12:13:43.027 回答
3

这是一个类似的例子,取自Real World Haskell,第 7 章,这对你来说是一个很好的资源。

main = do
   putStrLn "Greetings!  What is your name?"
   inpStr <- getLine
   putStrLn $ "Welcome to Haskell, " ++ inpStr ++ "!"

既然您知道如何读取字符串并打印它们,那么您面临的唯一挑战就是创建一个包含两个字符串的数组并将它们打印出来。提示:试试这个show命令。

如果您仍需要帮助,请向我们展示您的尝试,并附上您收到的任何错误消息。

于 2013-06-11T12:07:41.340 回答