Different behaviour of Int and Integer?
The followng snippet contains a solution for exercise 3 on page 69 (write a function mean
to calculate the mean of a list).
While writing some QuickCheck tests to verify whether the its results are more or less sane, I found that on my system (ghc 6.12.3, Haskell Platform 2010.2.0.0 on 32-but Ubuntu 10.4) the tests work for Integer
inputs, but not for Int
ones. Any idea on why?
import Test.QuickCheck
-- From text and previous exercises
data List a = Cons a (List a)
| Nil
deriving (Show)
fromList :: [a] -> List a
fromList [] = Nil
fromList (x:xs) = Cons x (fromList xs)
listLength :: List a -> Int
listLength Nil = 0
listLength (Cons x xs) = 1 + listLength xs
-- Function ``mean`` is the aim of this exercise
开发者_Go百科mean :: (Integral a) => List a -> Double
mean Nil = 0
mean (Cons x xs) = (fromIntegral x + n * mean xs) / (n + 1)
where n = fromIntegral (listLength xs)
-- To overcome rounding issues
almostEqual :: Double -> Double -> Bool
almostEqual x y = (abs (x - y)) < 0.000001
-- QuickCheck tests for ``mean``
prop_like_arith_mean :: (Integral a) => [a] -> Property
prop_like_arith_mean xs = not (null xs) ==>
almostEqual
(mean (fromList xs))
(fromIntegral (sum xs) / fromIntegral (length xs))
prop_sum :: (Integral a) => [a] -> Bool
prop_sum xs = almostEqual
(fromIntegral (length xs) * mean (fromList xs))
(fromIntegral (sum xs))
-- This passes:
check_mean_ok =
quickCheck (prop_like_arith_mean :: [Integer] -> Property) >>
quickCheck (prop_sum :: [Integer] -> Bool)
-- This fails:
check_mean_fail =
quickCheck (prop_like_arith_mean :: [Int] -> Property) >>
quickCheck (prop_sum :: [Int] -> Bool)
main = check_mean_ok >>
check_mean_fail
Int
is based on the underlying system's int implementation, and will probably the same lower and upper limits as the underlying system (but at least a range of [ -2^29, 2^29 - 1]. Integer
has arbitrary precision. Therefore you might be seeing an overflow or underflow when you use Int
.
精彩评论