PROPOSAL: toBoundedIntegral: an adaptation of fromIntegral that respects bounds
Sean Leather
sean.leather at gmail.com
Wed Nov 12 07:14:49 UTC 2014
Inspired by conversations recent [1] and not-so-recent [2] and by my own
past wish for this, I propose adding the following function to base:
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:
https://gist.github.com/spl/1986c9ff0b2416948957
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
[1] Evan Laforge:
http://thread.gmane.org/gmane.comp.lang.haskell.cafe/113600/focus=113648
[2] Stephen Paul Weber:
http://thread.gmane.org/gmane.comp.lang.haskell.cafe/102613/focus=64686
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/libraries/attachments/20141112/6c539425/attachment-0001.html>
More information about the Libraries
mailing list