结合sqrt和floor

时间:2016-11-15 20:58:27

标签: haskell types

尝试实现一个函数来列出某些数字范围内的所有素数,我知道当我检查因素时,我不必检查该数字的sqrt之外。

factors n = [x | x <- [1..(floor (sqrt n))], mod n x == 0]
prime n = factors n == [1,n]
listPrimesFromTill n z = [ xs | xs <- [n..z], prime xs == True]

我一直在寻找答案,我尝试了各种方法,比如使用

进行类型检查
factors :: (RealFrac b, Integral c, Floating b) => b -> c

但没有运气。

感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

看起来你看了你编写的代码,然后想出了类型。一般来说,Haskell开发是另一种方式:首先你弄清楚类型,然后你实现这些功能。 factors应该包含哪种类型?好吧,你只能对整数进行分解,所以这类似的东西,所以这看起来很明智:

factor :: Integral a => a -> [a]

现在尝试编译代码时出现以下错误:

Could not deduce (Floating a) arising from a use of `sqrt` from the context (Integral a)

Could not deduce (RealFrac a) arising from a use of `sqrt` from the context (Integral a)

它抱怨您指定了Integral aFloating a需要sqrt。我们可以通过usinf fromIntegral执行此操作:

sqrt         ::          Floating a => a -> a
fromIntegral :: (Integral a, Num b) => a -> b

factors :: Integral a => a -> [a]       vvvvvvvvvvvvvv
factors n = [x | x <- [1..(floor (sqrt (fromIntegral n)))], mod n x == 0]

为了保持可读性,

factors n = [x | x <- [1..isqrt n], mod n x == 0]
    where isqrt = floor . sqrt . fromIntegral