[Haskell-cafe] Fastest saturating add?

amindfv at mailbox.org amindfv at mailbox.org
Sun Jan 14 20:27:04 UTC 2024


I have a function that's called many (many) times, which involves a saturating addition (addition without overflow).

In other words, I'd like ((254 :: Word8) + 10) to equal 255 (which is maxBound::Word8), not 8 (which is what you get with overflow).

My current code, without particular regard to performance, is simply:

    satAdd :: Word8 -> Word8 -> Word8
    satAdd x y =
       let m = x + y
       in if m < x then 255 else m

This seems like the type of code somebody's already worked on the performance for, though I can't find much Haskell-specific in searches online.

Is there a faster way to do this?

Thanks!
Tom


More information about the Haskell-Cafe mailing list