[Haskell-beginners] A sort of fold for bits

Mario Lang mlang at delysid.org
Wed Mar 27 01:08:15 UTC 2019


I have written the following function for "iterating" over all set bits
in a Bits instance:

foldBits :: (Bits bits, Num bits) => (a -> Int -> a) -> a -> bits -> a
foldBits _ a 0 = a
foldBits f a n = foldBits f (f a lsb) (n `clearBit` lsb) where
  lsb = countTrailingZeros n

The type signature mimmicks foldl.
However, composing several calls to foldBits ends up pretty messy:

foldBits f (foldBits f (foldBits f [] value1) value2) value3

So I was thinking, maybe I should just flip the final arguments to make
composition easier:

fooBits :: (Bits bits, Num bits) => (a -> Int -> a) -> bits -> a ->  a
fooBits _ 0 a = a
foldBits f n a = foldBits f (n `clearBit` lsb) (f a lsb) where
  lsb = countTrailingZeros n

fooBits f value3 . fooBits f value2 . fooBits f value1 $ []

This looks more tidy.  However, now that I am no longer mimmicking
foldl, I am sort of at a loss how to name this beast.

iterBits comes to bind, but this isn't really like iterate.

I know, this question might look silly, but good naming conventions seem
to make it easier for me to reason about the code.

Any suggestions?

P.S.: Mimmicking foldl is probably wrong as well, since this isn't
really a fold, is it?


More information about the Beginners mailing list