我有一个函数appendLetters::[[Char]] -> [[Char]]
。当我尝试使用 iterate
调用此函数时,如下所示:iterateappendLetters [""]
,ghci 告诉我:
Couldn't match type '[Char]' with 'Char'
Expected type: [Char] -> [Char]
Actual type: [[Char]] -> [[Char]]
In the first argument of 'iterate', namely 'appendLetters'
In the second argument of 'genericTake', namely
'(iterate appendLetters [""])'
In the expression: genericTake n (iterate appendLetters [""])
Couldn't match expected type 'Char' with actual type `[Char]'
In the expression: ""
In the second argument of 'iterate', namely '[""]'
In the second argument of 'genericTake', namely
'(iterate appendLetters [""])'
失败,已加载模块:无。
为什么iterate
期望有这些参数类型?我怎样才能让它发挥作用?
提前致谢。
编辑:完整代码:
wordsOfLength :: [Char] -> Integer -> [[Char]]
wordsOfLength alphabet n = genericTake n ( iterate appendLetters [""] ) where appendLetters words = [ atFirst ++ [letter] | atFirst <- words , letter <- alphabet ]
解释:wordsOfLength 应该采用一个字母表并在该字母表上创建长度为 n 的所有单词。这是一项家庭作业,我不想获得解决任务本身的帮助,而只想获得迭代函数的帮助。
最佳答案
表达式
iterate appendLetters [""]
的类型为 [[[Char]]]
(iterate::(a -> a) -> a -> [a]
,在您的情况下 a == [[Char]]
)。因此,genericTake
的结果将具有相同的类型。但是您的 wordsOfLength
函数的输出类型为 [[Char]]
,这会导致类型不匹配。
直观上,您将返回一个(超长)列表(可能的单词)列表,其中单词本身就是列表,因此它是[[[Char]]]
。
关于loops - Haskell 迭代参数类型不匹配,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19619013/