2

首先,感谢您抽出宝贵时间回答我的问题。

首先,请快速查看我的代码。您不必了解代码,只需注意类型即可。

这会返回一个错误,上面写着,

Couldn't match expected type `Int' with actual type `Integer'
Expected type: [Int]
  Actual type: [Integer]
In the first argument of `myfun', namely `primes'
In the expression: myfun primes

失败,加载模块:无。

如果我将类型更改为 Int 而不是 Integer,我可以成功运行此程序而不会出现错误,例如,“primes :: [Int]”

但是,我需要将其保持为整数,以使程序能够获取大量数字。

非常感谢您提前提供的帮助。

4

3 回答 3

2

错误来自(!!)myfun

myfun (a:ab) = fibs !! (a-1) : myfun(ab)

较新的 GHC 可能会通知您(我认为)。试试这个:

myfun (a:ab) = fibs !! ((fromInteger a)-1) : myfun(ab)

fromInteger它的结果类型是多态的,所以这里类型系统推断你想要一个Int. hoogle对这类问题非常了解。

于 2013-01-24T06:12:33.053 回答
0

的类型myfun派生自 的类型!!,即[a] -> Int -> a。如果您使用数字作为列表索引,则必须成功Int,无论如何,您的数字受列表容量的限制。

于 2013-01-24T06:12:06.593 回答
0

您的类型错误的原因是它(!!)具有 type [a] -> Int -> a,因此,myfun's 的类型被推断为[Int] -> [Integer]

如果你真的需要Integers,fromIntegral不会帮你;一旦质数超过,它只会导致您的应用程序以负索引崩溃maxBound

但是,(!!)渐近复杂度较差,因此最好的解决方案是重新设计您的算法,以免需要二次运行时行为。

For example, instead of traversing the entire list of fibs each pass, you can instead express the primes as a list of index intervals to drop:

> import Data.List
> intervals :: [Integer]
> intervals = zipWith (-) (tail primes) primes

and collect the results of dropping prime intervals from the fibs:

> partC :: [Integer]
> partC = map head $ scanl (flip genericDrop) (tail fibs) intervals

I have used tail fibs here since you skip the first number in the fibonacci sequence.

于 2013-01-26T04:48:34.690 回答