Haskell 中存在递归和类型不匹配问题
-- genrep
genrep :: a -> Int -> [a]
genrep a n
| n == 0 = []
|otherwise = a ++ genrep (a (n-1))
所以我试图在 haskell 中创建一个简单的复制函数 - 该函数将采用泛型类型 a 并将其复制 n 次。然而,上面的方法似乎不起作用。我不断收到此错误代码:
*** Expression : a ++ genrep (a (n - 1))
*** Term : genrep (a (n - 1))
*** Type : Int -> [b]
*** Does not match : [a]
任何人都可以告诉我发生了什么事吗?这个函数对我来说看起来是正确的,但 Haskell 似乎不喜欢这个。
-- genrep
genrep :: a -> Int -> [a]
genrep a n
| n == 0 = []
|otherwise = a ++ genrep (a (n-1))
So I'm trying to make a simple replication function in haskell - one that would take a generic type a and replicate it n times. However, the above does not seem to work. I keep getting this error code:
*** Expression : a ++ genrep (a (n - 1))
*** Term : genrep (a (n - 1))
*** Type : Int -> [b]
*** Does not match : [a]
Can anyone tell me what's going on? The function looks correct to me, but Haskell doesn't seem to like this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将此:更改
为:
您当前的版本在需要两个参数时仅使用一个参数递归调用
genrep
。不需要额外的括号。编辑:我修复了上面的代码以包含
[a]
而不仅仅是a
。对此感到抱歉。这实际上是我建议你做的:Change this:
to this:
Your current version calls
genrep
recursively with only one argument when it expects two. The extra parenthesis aren't required.Edit: I fixed up the above code to include the
[a]
instead of justa
. Sorry about that. This is actually what I'd suggest you do:你也可以这样写:
甚至:
由于复制存在:
http://hackage.haskell .org/packages/archive/base/latest/doc/html/src/GHC-List.html#replicate
如果您不知道它的名称,您可以使用此 Hoogle 搜索找到它:
http://www.haskell.org/ hoogle/?hoogle=a+-%3E+Int+-%3E+%5Ba%5D
通常你不必手动编写这种递归,你可以重用诸如 take 或 Repeat 之类的函数。
You can also write it:
Or even:
Since replicate exists:
http://hackage.haskell.org/packages/archive/base/latest/doc/html/src/GHC-List.html#replicate
If you don't know its name, you can find it by using this Hoogle search:
http://www.haskell.org/hoogle/?hoogle=a+-%3E+Int+-%3E+%5Ba%5D
Usually you don't have to write this kind of recursion by hand, you can reuse functions like take or repeat.