关于转换为浮点数的Haskell类型问题

时间:2020-05-19 13:33:22

标签: haskell

我有以下代码可以测试素性

prime x n = if (n==1) then True else (if (mod x n == 0) then False else prime x (n-1))

但是我想创建一个单独的函数,这样我只需输入1个数字,就像这样:

isPrime x = prime x (floor(sqrt(x)))

但是,尝试此操作时出现错误:

 Ambiguous type variable `a0' arising from a use of `isPrime'
  prevents the constraint `(Integral a0)' from being solved.

我也想尝试使用部分函数来应用它,但是我也无法使它起作用。任何建议和帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

实际上,不首先计算平方根就更容易解决。相反,应从较小的n开始,然后向上{em> up 处理x的平方根(您可以通过比较n * nx来检测)。

-- Treat 1 and 2 as base cases so we can increment n a little faster;
-- The interesting values of n are the odd integers 3, 5, 7, ...
prime 1 _ = False
prime 2 _ = True
prime x n | n * n > x = True
          | mod x n == 0 = False
          | otherwise = prime x (n + 2)

isPrime x = prime x 3

(效率较低,因为重复计算n*n比计算平方根更昂贵。但是,如果您担心效率,那么您将实现Erastosthenes筛网或类似工具,而不是测试每个潜在的奇数因子。)