Add with translation to Word8

I cannot find a function addWithCarry :: Word8 -> Word8 -> (Word8, Bool)

already defined in base

. The only feature described as taking care of transfers seems to be addIntC#

in GHC.Prim

, but it's never pushed up through the various levels of abstraction.

I could obviously roll my own by checking if the output is in range, which is actually what I am doing now, but I would rather reuse the (potentially more efficient) already defined one.

Is there such a thing?

+3


source to share


2 answers


If you look at the source for the Word8 Num instance , you can see that everything is done by converting to an Word#

unboxed value and performing operations on that, and then narrowing down to an 8-bit value. I suspected that a comparison with this value Word#

would be more efficient, so I implemented such a thing. This is available in lpaste (which is easier for me to read than StackOverflow).

Note that it includes both a test suite and a criterion criterion. On my system, all the various tests take ~ 31ns for the boxed version (user5402 implementation) and ~ 24ns for the primer versions.



An important function from lpaste above primops

which:

primops :: Word8 -> Word8 -> (Word8, Bool)
primops (W8# x#) (W8# y#) =
    (W8# (narrow8Word# z#), isTrue# (gtWord# z# 255##))
  where
    z# = plusWord# x# y#

      

+2


source


The way to do it:



addWithCarry :: Word8 -> Word8 -> (Word8, Bool)
addWithCarry x y = (z, carry)
  where z = x + y
        carry = z < x

      

0


source







All Articles