[Haskell-cafe] Trying to write 'safeFromInteger'

Max Rabkin max.rabkin at gmail.com
Tue Apr 7 17:53:38 EDT 2009


On Tue, Apr 7, 2009 at 11:43 PM, Henning Thielemann
<lemming at henning-thielemann.de> wrote:
>
> 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.

Of course.

It can, however, be done:

safeFromInteger :: (Num b, Integral b, Bounded b) => Integer -> Maybe b
safeFromInteger i = let result = fromInteger i in
   if i > (toInteger $ maxBound `asTypeOf` result)
     then Nothing
     else Just result

Thank you, laziness!

> (safeFromInteger 1000000000000000000000000) :: Maybe Int
Nothing
> (safeFromInteger 100000) :: Maybe Int
Just 100000

--Max


More information about the Haskell-Cafe mailing list