Unw*_*ast 7 string haskell list fold
我在使这个功能工作时遇到了很多麻烦:
concatenate :: [String] -> String
Run Code Online (Sandbox Code Playgroud)
它被设计为简单地获取字符串列表并返回单个字符串,该字符串是列表中每个元素从头到尾连接的结果.我想留在内部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)
Run Code Online (Sandbox Code Playgroud)
我对Haskell 很新,所以请随意笑.只要还包括适合新手的解释,预计会受到苛刻,并受到欢迎.感谢您的帮助.
Sho*_*hoe 11
你实际上不需要那里的递归调用.该函数foldr已经模拟了递归调用.您需要做的就是使用:
concatenate :: [String] -> String
concatenate ls = foldr (++) "" ls
Run Code Online (Sandbox Code Playgroud)
并且记住已经有一个concat函数,它更通用,因为它适用于任何列表列表(而不是简单的字符串列表).
| 归档时间: |
|
| 查看次数: |
7391 次 |
| 最近记录: |