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.<div><br><br><div class="gmail_quote">
On Sat, Mar 27, 2010 at 7:44 PM, Maciej Piechotka <span dir="ltr"><<a href="mailto:uzytkownik2@gmail.com">uzytkownik2@gmail.com</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">
<div><div></div><div class="h5">On Fri, 2010-03-26 at 14:23 -0400, Ashish Agarwal wrote:<br>
> Is there an alternative implementation of the types Word8, Word16,<br>
> etc. that disallow overflow? For example, currently:<br>
><br>
><br>
> Prelude Word> (fromInteger 256) :: Word8<br>
> 0<br>
><br>
><br>
> I'd like a type whose constructors disallow this.<br>
><br>
><br>
<br>
</div></div>safeConvert :: (Integral a, Integral b) :: a -> Maybe b<br>
safeConvert x | fromIntegral y == x = Just $! y<br>
| otherwise = Nothing<br>
where y = fromIntegral x<br>
<br>
You can write:<br>
<br>
newtype Safe a = Safe a deriving Eq<br>
<br>
instance Show a => Show (Safe a) where<br>
show (Safe x) = show x<br>
<br>
instance Integral a => Num (Safe a) where<br>
(Safe x) + (Safe y) = Safe $! x + y<br>
(Safe x) * (Safe y) = Safe $! x * y<br>
(Safe x) - (Safe y) = Safe $! x - y<br>
negate (Safe y) = Safe $! negate y<br>
abs (Safe y) = Safe $! abs y<br>
signum (Safe y) = Safe $! signum y<br>
fromInteger x =<br>
Safe $! fromMaybe (error "overflow") (safeConvert x)<br>
<br>
...<br>
<br>
if you want<br>
<br>
Regards<br>
<br>_______________________________________________<br>
Beginners mailing list<br>
<a href="mailto:Beginners@haskell.org">Beginners@haskell.org</a><br>
<a href="http://www.haskell.org/mailman/listinfo/beginners" target="_blank">http://www.haskell.org/mailman/listinfo/beginners</a><br>
<br></blockquote></div><br></div>