我在让这个功能工作时遇到了很多麻烦:
concatenate :: [String] -> String
它旨在简单地获取字符串列表并返回单个字符串,该字符串是列表中每个元素从头到尾连接的结果。我试图留在
map
, foldl
, 和 foldr
功能。我觉得我知道这些函数的概念做得很好,但我遇到的最常见的问题是我遇到了类型冲突。例如,GHC 将期望一个 [Char],我将输入显然试图在我不知道的情况下使用 [[Char]] 的代码。例如:
concatenate (x:xs) = foldr (++) x (concatenate xs)
我得到以下编译错误:
Couldn't match type `Char' with `[Char]'
Expected type: [[Char]]
Actual type: String
In the return type of a call of `concatenate'
In the third argument of `foldr', namely `(concatenate xs)'
In the expression: foldr (++) x (concatenate xs)
我对 Haskell 很陌生,所以请随意大笑。只要还包括适合新手的解释,就可以预料到苛刻并受到欢迎。感谢您的任何帮助。
最佳答案
您实际上不需要那里的递归调用。函数foldr
已经模拟了递归调用。您需要做的就是使用:
concatenate :: [String] -> String
concatenate ls = foldr (++) "" ls
请记住,有一个
concat
function已经,这是更通用的,因为它适用于任何列表列表(而不是简单的字符串列表)。
关于string - 在 Haskell : [String] -> String 中创建连接函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28575452/