Haskell 中存在递归和类型不匹配问题

发布于 2024-10-24 01:43:00 字数 456 浏览 3 评论 0原文

-- 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

醉酒的小男人 2024-10-31 01:43:00

将此:更改

| otherwise = a ++ genrep (a (n-1))

为:

| otherwise = [a] ++ genrep a (n-1)

您当前的版本在需要两个参数时仅使用一个参数递归调用 genrep 。不需要额外的括号。

编辑:我修复了上面的代码以包含 [a] 而不仅仅是 a。对此感到抱歉。这实际上是我建议你做的:

genrep :: a -> Int -> [a]
genrep a 0 = []
genrep a n = a : genrep a (n-1)

Change this:

| otherwise = a ++ genrep (a (n-1))

to this:

| otherwise = [a] ++ genrep a (n-1)

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 just a. Sorry about that. This is actually what I'd suggest you do:

genrep :: a -> Int -> [a]
genrep a 0 = []
genrep a n = a : genrep a (n-1)
逆光下的微笑 2024-10-31 01:43:00

你也可以这样写:

genrep :: a -> Int -> [a]
genrep a n = take n (repeat a)

甚至:

genrep = flip replicate

由于复制存在:
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:

genrep :: a -> Int -> [a]
genrep a n = take n (repeat a)

Or even:

genrep = flip replicate

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文