【发布时间】:2023-04-02 10:05:02
【问题描述】:
我正在尝试创建函数primes,它是一个素数列表,但不知何故我失败了。编译器抛出一个我不知道如何解决的错误:
错误:
Ambiguous type variable 'a0'
代码:
candidates :: [Integer]
candidates = [2]++[3,5..]
primes :: [Integer]
primes = filter is_prime candidates
is_prime :: Integer -> Bool
is_prime candidate
| candidate == 1 = False
| candidate == 2 = True
| candidate == 3 = True
| otherwise = r_is_prime candidate 0
-- r as recursive
r_is_prime :: Integer -> Integer -> Bool
r_is_prime candidate order
| n_th_prime >= max_compared_prime = True
| candidate `mod` n_th_prime == 0 = False
| otherwise = if (r_is_prime candidate (order+1) ) then True else False
where
n_th_prime = candidates !! fromIntegral(order)
-- this is the line that throws an error...
max_compared_prime = fromIntegral ( ceiling ( fromIntegral ( sqrt ( fromIntegral candidate))))
【问题讨论】:
-
primes = 2 : 3 : [n | n<-[5,7..], foldr (\p r-> p*p>n || (rem n p /= 0 && r)) True (tail primes)]