Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can Integer have an instance of Enum? toEnum and fromEnum only use Int, which is limited

Tags:

haskell

I don't fully understand why this works just fine:

[9223372036854775809..9223372036854775815] :: [Integer]

Those are integers that are larger than maxBound :: Int. Yet these are the type signatures of the two crucial Enum functions:

toEnum :: Int -> a
fromEnum :: a -> Int

As you can see, they have Int, which is bounded.

So why did the above work?

Clarification:

The point of my question is this: Isn't enumFromTo defined in terms of toEnum and fromEnum? And since those two work only on regular Ints, how can enumFromTo (for which .. is a syntactic sugar) work for Integers?

like image 680
haskellHQ Avatar asked Jan 31 '16 21:01

haskellHQ


1 Answers

enumFromTo for Integer is not defined in terms of toEnum and fromEnum, which indeed would cause a loss in representation as you mentioned. You can read the implementation here, which calls enumDeltaToInteger :: Integer -> Integer -> Integer -> [Integer].

instance  Enum Integer  where
    succ x               = x + 1
    pred x               = x - 1
    toEnum (I# n)        = smallInteger n
    fromEnum n           = I# (integerToInt n)

    {-# INLINE enumFrom #-}
    {-# INLINE enumFromThen #-}
    {-# INLINE enumFromTo #-}
    {-# INLINE enumFromThenTo #-}
    enumFrom x             = enumDeltaInteger   x 1
    enumFromThen x y       = enumDeltaInteger   x (y-x)
    enumFromTo x lim       = enumDeltaToInteger x 1     lim
    enumFromThenTo x y lim = enumDeltaToInteger x (y-x) lim
like image 113
hao Avatar answered Oct 18 '22 23:10

hao