gpt4 book ai didi

haskell - 为什么 Haskell 将我的 Num 类型解释为 Enum?

转载 作者:行者123 更新时间:2023-12-02 17:14:41 24 4
gpt4 key购买 nike

我正在尝试在 Haskell 中编译以下函数来模拟其常数在数字列表中指定的多项式的微分:

diff :: (Num a) => [a] -> [a]
diff [] = error "Polynomial unspecified"
diff coeff = zipWith (*) (tail coeff) [0..]

Haskell 拒绝编译它,给了我以下原因:

Could not deduce (Enum a) from the context (Num a)
arising from the arithmetic sequence `0 .. ' at fp1.hs:7:38-42
Possible fix:
add (Enum a) to the context of the type signature for `diff'
In the third argument of `zipWith', namely `[0 .. ]'
In the expression: zipWith (*) (tail coeff) ([0 .. ])
In the definition of `diff':
diff coeff = zipWith (*) (tail coeff) ([0 .. ])

为什么 Haskell 将 [0..] 列表视为 Enum 类型,以及如何解决这个问题。请记住,我想在这里利用惰性求值,因此有无限列表。

最佳答案

[0..]enumFrom 0 的语法糖,在类 Enum 中定义。因为您想要生成带有 [0..]a 列表,所以编译器要求 a 位于类 Enum< 中.

您可以将 Enum a 添加到函数的类型签名中,或者通过生成 [0..]::[Integer] 并使用来解决它fromInteger(在 Num 类中定义)从中获取 [a]:

diff :: (Num a) => [a] -> [a]
diff [] = error "Polynomial unspecified"
diff coeff = zipWith (*) (tail coeff) (map fromInteger [0..])

关于haskell - 为什么 Haskell 将我的 Num 类型解释为 Enum?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1533585/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com