看起來你看着你寫的代碼,並計算出後的類型。一般來說,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