I'm trying to make a function to convert an Integer to an Int and wish
more safety than fromInteger supplies. Specifically, I want the
function to fail if the Integer does not fit in an Int (sadly,
fromInteger seems to quietly overflow).
My first attempt was:
> safeFromInteger :: (Integral a, Bounded a) => Integer -> a
> safeFromInteger x | toInteger maxBound >= x = fromInteger x
Unfortunately, this leads to:
> Ambiguous type variable `a' in the constraints:
> `Integral a'
> arising from a use of `toInteger' at xxx.lhs:19:20-37
> `Bounded a'
> arising from a use of `maxBound' at xxx.lhs:19:30-37
> Probable fix: add a type signature that fixes these type variable(s)
I thought maybe the problem was that my constraint didn't offer enough
constraining, and realistically I was only interested in Ints, so I
changed it to:
> safeFromInteger :: Integer -> Int
> safeFromInteger x | toInteger maxBound >= x = fromInteger x
Unfortunately this leads to exactly the same error, so the problem
doesn't seem to be with the constraints.
Can anyone give some insight on how I need to structure this to get it
to type correctly?
Much thanks,
Mike


|