5

在 haskell 中计算 2^8 的一种方法是编写

product(replicate 8 2)

当试图为此创建一个函数时,定义如下......

power1 :: Integer →  Integer → Integer
power1 n k | k < 0 = error errorText
power1 n 0 = 1
power1 n k = product(replicate k n)

我收到以下错误:

Couldn't match expected type 'Int' against inferred type 'Integer'

我的猜测是我必须在某处使用 fromInteger 函数......我只是不确定在哪里或如何?是接口还是fromInteger,应该怎么用?

谢谢

4

3 回答 3

11

首先,永远不要使用 fromInteger。使用 fromIntegral。

您可以通过查看复制的类型来查看类型错误的位置:

replicate :: Int -> a -> [a]

所以当你给它'k'作为参数时,你已经通过类型声明断言它是一个整数,我们有一个类型错误。

一个更好的方法是使用 genericReplicate:

genericReplicate :: (Integral i) => i -> a -> [a]

那么:

power1 n k = product (genericReplicate k n)
于 2009-11-02T19:40:30.547 回答
3

您还应该查看错误消息的其余部分,它会准确地告诉您问题的答案:

Couldnt match expected type 'Int' against inferred type 'Integer'
In the first argument of 'replicate', namely 'k'
In the first argument of 'product', namely '(replicate k n)'
In the expression: product (replicate k n)

“在复制的第一个参数中”。那是添加的地方fromIntegral

于 2009-11-03T22:55:32.173 回答
2

也许更简单的解决方案是将函数的类型定义更改为:

power1 :: Integer -> Int -> Integer
于 2009-11-02T19:45:27.933 回答