我正在寫一個函數來查找實數的整數因數。當我運行的代碼,我得到以下錯誤:Haskell中的類型問題
Clean solutions.hs:70:33:
Could not deduce (Integral a) arising from a use of `truncate'
from the context (RealFrac a)
bound by the type signature for divisors :: RealFrac a => a -> [a]
at Clean solutions.hs:70:1-74
Possible fix:
add (Integral a) to the context of
the type signature for divisors :: RealFrac a => a -> [a]
In the first argument of `(==)', namely `(truncate (n/x))'
In the expression: (truncate (n/x)) == (n/x)
In the first argument of `filter', namely
`(\ x -> (truncate (n/x)) == (n/x))'
Clean solutions.hs:70:59:
Could not deduce (Enum a)
arising from the arithmetic sequence `2.0, 3.0 .. n/2'
from the context (RealFrac a)
bound by the type signature for divisors :: RealFrac a => a -> [a]
at Clean solutions.hs:70:1-74
Possible fix:
add (Enum a) to the context of
the type signature for divisors :: RealFrac a => a -> [a]
In the second argument of `filter', namely `[2.0, 3.0 .. n/2]'
In the second argument of `(:)', namely
`filter (\ x -> (truncate (n/x)) == (n/x)) [2.0, 3.0 .. n/2]'
In the expression:
1
: filter (\ x -> (truncate (n/x)) == (n/x)) [2.0, 3.0 .. n/2]
我發現很難理解我在做什麼錯的,儘管花費一兩個小時在Haskell刷牙的類型。我的代碼如下:
divisors :: RealFrac a => a -> [a]
divisors n = 1 : filter (\x -> (truncate (n/x)) == (n/x)) [2.0, 3.0.. n/2]
謝謝, 山姆。
尋找除數是真的不是你應該使用'RealFrac'的。它更像是一個整體,所以'divisors :: Integral a => a - > [a]'會更合適。我懷疑你是因爲用'/'分隔而去了'RealFrac'。如果這是正確的,使用'quot'(或可能'div')來除積分類型,'rem'(或'mod',如果你想積極保留負數),除數n = 1:過濾器((== 0)。(n'rem'))[2 .. n'quot' 2]''是您嘗試的相應(低效率)實現。 –
請定義「實數的整數除數」。什麼是7.6的整數除數,或pi,應該是什麼? – chirlu