[Haskell-cafe] Trying to write 'safeFromInteger'

Henning Thielemann lemming at henning-thielemann.de
Tue Apr 7 17:43:31 EDT 2009

On Tue, 7 Apr 2009, Max Rabkin wrote:

> The problem with your code is that the type of maxBound is
> unspecified. You need (maxBound `asTypeOf` i), or enable
> ScopedTypeVariables and use (maxBound :: a) (I think).

i is Integer, so asTypeOf is not so easy to apply. I propose to write

safeFromIntegerAux :: (Num a, Integral a) =>
    a -> Integer -> Maybe a
safeFromIntegerAux mb i =
   if i > toInteger mb
     then Nothing
     else Just (fromInteger i)

safeFromInteger = safeFromIntegerAux maxBound

Btw. this is another instance where my beloved toMaybe function is useful. :-)

More information about the Haskell-Cafe mailing list