我遇到了一個簡單的Haskell程序問題。它應該將數字n-1分解成(2^r)s形式,其中n是卡邁克爾數。這與我的問題並不緊密相關,但它是以下功能集的目的所在。Haskell數字類型挫折
divides::Int->Int->Bool
divides x y = not $ y `mod` x == 0
carmichaeltwos::Int->Int
carmichaeltwos n
| not $ divides 2 n =0
| otherwise = (+ 1) $ carmichaeltwos (n/2)
carmichaelodd::Int->Int
carmichaelodd n
| not $ divides 2 n = n
| otherwise = carmichaelodd (n/2)
factorcarmichael::Int->(Int, Int)
factorcarmichael n = (r, s)
where
nminus = n-1
r = carmichaeltwos nminus
s = carmichaelodd nminus
當我嘗試這個加載到GHCI,Haskell中吐奶:
No instance for (Fractional Int)
arising from a use of `/'
Possible fix: add an instance declaration for (Fractional Int)
In the first argument of `carmichaelodd', namely `(n/2)'
In the expression: carmichaelodd (n/2)
In an equation for `carmichaelodd':
carmichaelodd n
| not $ divides 2 n = n
| otherwise = carmichaelodd (n/2)
我知道的功能/已鍵入(/)::(一分數)=> A->一 - > a,但我看不出如何修復我的程序以使其很好地工作。
另外,我意識到我基本上在factorcarmichael函數中計算兩次相同的東西。我想不出任何簡單的方法來將數字分解成一個通道,並得到我想要的元組作爲答案。
jwodder,說明了他們的答案最好的解決辦法,但值得注意的是,你可以用'fromIntegral'轉換的'實例Integral'到'Fractional'和'round' /'floor' /'ceiling' /'truncate'的實例中,以轉換RealFrac的一個實例(比如'Float','Double','Rational'等等)轉換爲'Integral'的實例。 – ehird 2012-03-25 19:10:14