loops - Haskell 迭代参数类型不匹配,为什么?

标签 loops haskell

我有一个函数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/

相关文章:

memory-management - 为什么 Haskell 编译器不促进确定性内存管理?

haskell - Haskell中没有错误消息

javascript - 如何通过操作特定键从对象创建 HashMap

vba - Excel VBA Exit For 在 If block 内不起作用

php - 使用基于设备宽度的 PHP 变量替换图像源值

haskell - 在过滤器函数中使用逻辑 && 连接谓词

haskell - 在 Haskell 中编写有状态函数

python - 通过循环将多个列表组装成一个列表

c - 使用 malloc 循环来保证 malloc 的结果不好吗?

haskell - 在 Haskell 中捕获异常