[Haskell-beginners] Re: overflow safe Word types
Maciej Piechotka
uzytkownik2 at gmail.com
Sat Mar 27 19:44:34 EDT 2010
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
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 836 bytes
Desc: This is a digitally signed message part
Url : http://www.haskell.org/pipermail/beginners/attachments/20100327/b0128f30/attachment.bin
More information about the Beginners
mailing list