[英]Ambiguous type variable in combination of sqrt and floor
嘗試實現一個在某個數字范圍內列出所有素數的功能時,我知道當我檢查因素時,不必檢查該數字的平方根。
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
但沒有運氣。
任何幫助表示贊賞!
似乎您查看了所編寫的代碼並弄清楚了類型。 通常,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
但是它需要為sqrt
Floating a
。 我們可以通過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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.