【发布时间】:2015-01-21 06:46:49
【问题描述】:
欧拉计划第 7 题:第 10 001 个素数是多少?
这是一个接受单个参数 (10001) 并返回第 10001 个素数的函数。 GHCi 没有给我任何问题:
p007nthPrime x = primes !! (x - 1)
where
primes :: [Integer]
primes = sieve [2..]
where
sieve (p:xs) = p : sieve [x|x <- xs, x `mod` p > 0]
现在,作为一名优秀的 Haskeller,我想做一个类型签名。但是,将p007nthPrime :: (Integral a) => a -> a 放在顶部会引发此错误:
projecteuler.hs:81:29:
Couldn't match type `Integer' with `Int'
Expected type: Int
Actual type: a
In the first argument of `(-)', namely `x'
In the second argument of `(!!)', namely `(x - 1)'
In the expression: primes !! (x - 1)
Failed, modules loaded: none.
并插入p007nthPrime :: (Num a) => a -> a 做同样的事情。这个函数的正确类型签名是什么?
【问题讨论】:
-
好吧,
!!的类型为[a] -> Int -> a(hackage.haskell.org/package/base-4.7.0.2/docs/…);索引是固定类型Int。因此,您的函数必须具有(Integral a) => Int -> a类型。 -
让 ghci 告诉你
:type p007nthPrime的类型签名是什么