Loops Haskell迭代参数类型不';不匹配,为什么?
我有一个函数Loops Haskell迭代参数类型不';不匹配,为什么?,loops,haskell,Loops,Haskell,我有一个函数appendLetters::[[Char]]->[[Char]]]。当我尝试使用以下方法调用此函数时:iterate:iterate appendLetters[“”],ghci告诉我: Couldn't match type '[Char]' with 'Char' Expected type: [Char] -> [Char] Actual type: [[Char]] -> [[Char]] In the first argument of 'it
appendLetters::[[Char]]->[[Char]]]
。当我尝试使用以下方法调用此函数时: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 [""])'
失败,已加载模块:无
为什么iterate
希望有这些参数类型?我怎样才能让它工作
提前谢谢
编辑:完整代码:
wordsOfLength :: [Char] -> Integer -> [[Char]]
wordsOfLength alphabet n = genericTake n ( iterate appendLetters [""] ) where appendLetters words = [ atFirst ++ [letter] | atFirst <- words , letter <- alphabet ]
wordsOfLength::[Char]->Integer->[[Char]]
wordsOfLength字母表n=genericTake n(迭代appendLetters[“”]),其中appendLetters words=[atFirst++[letter]| atFirst表达式
iterate appendLetters [""]
具有类型[[[Char]]]
(迭代::(a->a)->a->[a]
,并且在您的情况下a=[[Char]]]
)。因此genericTake
的结果将具有相同的类型。但是wordsOfLength
函数具有输出类型[[Char]]
,这会导致类型不匹配
直观地说,您返回的是一个列表(超过可能单词的长度),其中单词本身就是列表,因此这是[[[Char]]]]
这个类型为我检查。:t迭代(未定义::[[Char]]->[[Char]])[“”
说结果是[[Char]]
。您能在使用此表达式的地方发布完整函数吗?更好的是,这是一个可运行的示例。另外,appendLetters
应该做什么?从您选择的类型来看,字母应该来自何处或应该附加到何处并不明显。我编辑了原始帖子,以便您能够更好地理解我的问题。谢谢用于查看我的问题。从另一个角度来看:您的问题不是迭代
,而是genericTake
。后者选择列表的前n个元素,从而生成一个新列表。您需要类似于genericIndex
的内容,从而生成索引n处的元素。(请注意,genericIndex
如果您给它一个负索引,它将使您的程序崩溃。)您的回答对我帮助很大,谢谢。现在一切都按预期进行了。