toBoundedIntegral :: (Integral a, Integral b, Bounded b) => a -> Maybe b
toBoundedIntegral x
| y > toInteger (maxBound `asTypeOf` z) = Nothing
| y < toInteger (minBound `asTypeOf` z) = Nothing
| otherwise = Just $! z
where
y = toInteger x
z = fromInteger y
This includes rules to optimize for many cases where we know the bounds at compile time. See the gist for the full implementation:
I'm not particularly concerned with the precise location of this function. It could start out in GHC.Int if there's controversy. Otherwise, Data.Int would be an option to avoid polluting the Prelude.
I chose the name to be descriptive of the result type, which is the more constrained type. The function that I started from [2] was called fromIntegralSafe, but I think “safe” is too ambiguous here. I did not find “toBoundedIntegral” in any package on Hackage.
I welcome review of the implementation and rules.
Discussion period: ~10 days if there is a strong desire to get it in GHC 7.10. (I would certainly like to see it get in.) Otherwise, I can make a package, and we can revisit the issue at another time.
Regards,
Sean