[Haskell-cafe] Trying to write 'safeFromInteger'
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.
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)
else Just result
Thank you, laziness!
> (safeFromInteger 1000000000000000000000000) :: Maybe Int
> (safeFromInteger 100000) :: Maybe Int
More information about the Haskell-Cafe