2016-11-15 73 views
0

試圖實現列出某些數字範圍內的所有素數的函數,我知道在檢查因素時我不必檢查該數字的sqrt以外的因素。sqrt和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 

檢查,但有沒有運氣。

任何幫助表示讚賞!

+2

是否有意義使用'Floating'作爲'factors'輸入約束?這意味着稱爲「因素3.14」是有效的。輸出應該是什麼? – crockeea

回答

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 a,但它需要Floating asqrt。我們可以通過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 
+0

這對我不起作用,它不適用於任何東西! –

+0

@FredPark請更具體。什麼不工作? – ThreeFx

+0

修改你的建議(這是有道理的)的代碼沒有找到我想要的範圍內的素數。 –