gpt4 book ai didi

list - Haskell IO 创建一个字符串列表并显示它

转载 作者:行者123 更新时间:2023-12-01 09:26:55 25 4
gpt4 key购买 nike

我正在尝试编写一个程序,允许用户通过一次输入一个字符串来构建一个字符串列表,并在每一步后显示该列表。

到目前为止,这是我的代码:

buildList :: [String] -> IO ()
buildList arr = do
putStr "Enter a line:"
str <- getLine
if str == "" then
return ()
else do
let newarr = arr : str
putStrLn ("List is now: " ++ newarr)
buildList newarr


listBuilder :: IO ()
listBuilder = do
buildList []

listBuilder 通过传入空列表来启动列表,我正在尝试使用递归,以便代码一直运行,直到用户输入空字符串。

它不工作,欢迎任何想法

这是一个需要的输入:

Enter a line: hello
List is now ["hello"]
Enter a line: world
List is now ["hello","world"]
Enter a line:

错误:

Couldn't match type `Char' with `[String]'
Expected type: [[String]]
Actual type: String
In the second argument of `(:)', namely `str'
In the expression: arr : str
In an equation for `newarr': newarr = arr : str

编辑:

由于线索和 show

的使用,这修复了它
buildList :: [String] -> IO ()
buildList arr = do
putStr "Enter a line:"
str <- getLine
if str == "" then
return ()
else do
let newarr = arr++[str]
putStrLn ("List is now: " ++ show newarr)
buildList newarr


listBuilder :: IO ()
listBuilder = do
buildList []

最佳答案

你可以通过

(a) 使用 arr++[str] 而不是 arr:str 将新字符串放在列表的末尾,因为 : 可以只能像singleThing:list,
那样使用 (b) 将 run-round 拆分为一个单独的函数,并且
(c) 使用 return 传递结果,以便您可以在程序的其他地方使用它

buildList arr = do
putStrLn "Enter a line:"
str <- getLine
if str == "" then
return arr
else do
tell (arr++[str])

tell arr = do
putStrLn ("List is now: " ++ show arr) -- show arr to make it a String
buildList arr

给予

Enter a line:
Hello
List is now: ["Hello"]
Enter a line:
world
List is now: ["Hello","world"]
Enter a line:

done

关于list - Haskell IO 创建一个字符串列表并显示它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21782595/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com