PROPOSAL: toBoundedIntegral: an adaptation of fromIntegral that respects bounds

Herbert Valerio Riedel hvr at gnu.org
Wed Nov 12 10:18:47 UTC 2014


On 2014-11-12 at 08:14:49 +0100, Sean Leather wrote:
> 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

Btw, a somewhat related approach I tuned heavily (but relies on 'Bits'
rather than 'Bounded')

http://hackage.haskell.org/package/int-cast-0.1.1.0/docs/Data-IntCast.html#v:intCastMaybe


More information about the Libraries mailing list