来计算在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,我应该如何使用它?

由于

有帮助吗?

解决方案

首先,从不使用fromInteger。使用fromIntegral。

可以看到,其中类型错误是通过观察复制的类型:

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

,所以当你连锁行业它数“k”作为一个参数,表示已断言是经由类型声明一个整数,我们有一个类型的错误。

这方面的一个较好的方法是使用genericReplicate:

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

所以那么:

power1 n k = product (genericReplicate k n)

其他提示

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

power1 :: Integer -> Int -> Integer

您应该查看错误消息的其余部分为好,它会告诉你完全回答你的问题:

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的地方。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top