Is there a general way to prevent overflows when summing lists?

Viewed 68

I'm working with ByteStrings, and by extension a lot of Word8. When i write sum word8List, the returned value is also Word8, but i know my data, and that sum is too large for a Word8. Should i avoid sum, or does it work differently than i think?

Is there some general function for summing numbers without overflowing, like Num a => a -> Integer?

1 Answers

The sum will use the (+) defined for that type, so for a Word8, it will make a wraparound.

You can however first perform a mapping, for example with fromIntegral :: (Integral a, Num b) => a -> b, and thus convert the numbers to another numeric type (like Integer, Word16, Word32, etc.). For example:

sum (map fromIntegral word8List) :: Integer
Related