Haskell repeated using fromIntegral when adding

I have a number of values Word8that I add together. Since this can lead to overflow, the result should be Word16.

Is there a better way to add all these values ​​than the following:

fromIntegral a + fromIntegral b + fromIntegral c + fromIntegral d + ...

which clutters the code without adding any clarity?

+4
source share
1 answer

If you need to mix operations (as you suggest in your comments), you can use this trick to bulk assign new variables

let [a', b', c', d'] = map fromIntegral [a, b, c, d]
in a' + b' - c' + d'

However, if you want to do a lot of this type of operation, it is probably easier for you to define your own "mixed" operators

let a !+ b = fromIntegral a + fromIntegral b
let a !- b = fromIntegral a - fromIntegral b

a !+ b !- c !+ d :: Word16
+6
source

All Articles