[Haskell-beginners] Re: overflow safe Word types

Ashish Agarwal agarwal1975 at gmail.com
Tue Mar 30 14:44:22 EDT 2010


Thanks for the answers. These options should work. I don't actually need to
do arithmetic on these values, just construct values that are not
out-of-bounds. Thus efficiency is not a major concern.


On Sat, Mar 27, 2010 at 7:44 PM, Maciej Piechotka <uzytkownik2 at gmail.com>wrote:

> On Fri, 2010-03-26 at 14:23 -0400, Ashish Agarwal wrote:
> > Is there an alternative implementation of the types Word8, Word16,
> > etc. that disallow overflow? For example, currently:
> >
> >
> > Prelude Word> (fromInteger 256) :: Word8
> > 0
> >
> >
> > I'd like a type whose constructors disallow this.
> >
> >
>
> safeConvert :: (Integral a, Integral b) :: a -> Maybe b
> safeConvert x | fromIntegral y == x = Just $! y
>              | otherwise           = Nothing
>              where y = fromIntegral x
>
> You can write:
>
> newtype Safe a = Safe a deriving Eq
>
> instance Show a => Show (Safe a) where
>        show (Safe x) = show x
>
> instance Integral a => Num (Safe a) where
>        (Safe x) + (Safe y) = Safe $! x + y
>        (Safe x) * (Safe y) = Safe $! x * y
>        (Safe x) - (Safe y) = Safe $! x - y
>        negate     (Safe y) = Safe $! negate y
>        abs        (Safe y) = Safe $! abs y
>        signum     (Safe y) = Safe $! signum y
>        fromInteger x       =
>          Safe $! fromMaybe (error "overflow") (safeConvert x)
>
> ...
>
> if you want
>
> Regards
>
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://www.haskell.org/mailman/listinfo/beginners
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/beginners/attachments/20100330/cfd8afe4/attachment.html


More information about the Beginners mailing list