看起来你看着你写的代码,并计算出后的类型。一般来说,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 a
,但它需要Floating 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
是否有意义使用'Floating'作为'factors'输入约束?这意味着称为“因素3.14”是有效的。输出应该是什么? – crockeea