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.
safeConvert :: (Integral a, Integral b) :: a -> Maybe bOn 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 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@haskell.org
http://www.haskell.org/mailman/listinfo/beginners