4 ms·
If your algorithm works on both 32-bit and 64-bit integers, then you can parameterize it: safeAdd :: (SmallInt i) => i -> i -> Maybe i safeAdd x y = if
by jhpriestley 15y ago
If your algorithm works on both 32-bit and 64-bit integers, then you can parameterize it:
safeAdd :: (SmallInt i) => i -> i -> Maybe i
safeAdd x y = if (maxBound - x) > y then Just (x + y) else Nothing
`maxBound` would be a member of the `SmallInt` typeclass, with different values for `Int32, `Int64`, `Int23`, etc.
- aristidb 15y agoBounded is the typeclass you want.
- jhpriestley 15y agoAh, right. I don't actually do much numerically sensitive programming. Why aren't Haskell's SmallInt functions parameterized over Int size, anyway? Of the points brought up in the blog post, this one seems the easiest to fix.