[英]Haskell iterate argument types don't match, why?
I have a function appendLetters :: [[Char]] -> [[Char]]
. 我有一个函数appendLetters :: [[Char]] -> [[Char]]
。 When I try to call this function in with iterate
like this: iterate appendLetters [""]
, ghci tells me: 当我尝试以如下iterate
方式调用此函数: iterate appendLetters [""]
,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 [""])'
Failed, modules loaded: none. 失败,模块已加载:无。
Why does iterate
expect to have these argument types? 为什么iterate
期望具有这些参数类型? How can I make it work? 我该如何运作?
Thanks in advance. 提前致谢。
Edit: Full code: 编辑:完整代码:
wordsOfLength :: [Char] -> Integer -> [[Char]]
wordsOfLength alphabet n = genericTake n ( iterate appendLetters [""] ) where appendLetters words = [ atFirst ++ [letter] | atFirst <- words , letter <- alphabet ]
Explanation: wordsOfLength should take an alphabet and create all words of length n over this alphabet. 说明:wordsOfLength应该采用一个字母并在该字母上创建所有长度为n的单词。 This is a homework assignment and I don't want to get help with solving the task itself, but only with the iterate function. 这是一项家庭作业,我不想寻求解决任务本身的帮助,而只希望获得迭代功能。
The expression 表达方式
iterate appendLetters [""]
has type [[[Char]]]
( iterate :: (a -> a) -> a -> [a]
, and in your case a == [[Char]]
). 具有类型[[[Char]]]
( iterate :: (a -> a) -> a -> [a]
( iterate :: (a -> a) -> a -> [a]
,在您的情况下a == [[Char]]
))。 So the result of genericTake
will have the same type. 因此, genericTake
的结果将具有相同的类型。 But your wordsOfLength
function has the output type [[Char]]
, which causes the type mismatch. 但是您的wordsOfLength
函数具有输出类型[[Char]]
,这会导致类型不匹配。
Intuitively, you are returning a list (over lengths) of lists (of possible words), where words are lists themselves, so it's [[[Char]]]
. 直观地,您将返回一个列表(超过长度)(可能的单词)列表,其中单词本身就是列表,因此为[[[Char]]]
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.