[Haskell-cafe] convert a list of booleans into Word*

Roel van Dijk vandijk.roel at gmail.com
Wed Sep 30 06:20:01 EDT 2009


I wrote a few variants for fun. Probably equally inefficient. I
suggest you look at Data.Binary as Andrew suggested.


-- Your original function, but with a more generic type signature.
encodeBits :: Bits n => [Bool] -> n
encodeBits bs = go 0 0 bs
    where
      go n r []     = r
      go n r (b:bs) = go (n+1) (if b then setBit r n else clearBit r n) bs

-- Combine the flags with their index and then set bits when appropriate.
encodeBits2 :: Bits n => [Bool] -> n
encodeBits2 = foldr (\(n, b) x -> setBitIf b x n) 0 . zip [0..]
    where
      setBitIf False x _ = x
      setBitIf True  x n = setBit x n

-- Shift the result left while constructing and only toggle the first bit.
encodeBits3 :: Bits n => [Bool] -> n
encodeBits3 bs = foldr (\b x -> setBitIf b (x `shiftL` 1)) 0 bs
    where
      setBitIf False x = x
      setBitIf True  x = setBit x 0


More information about the Haskell-Cafe mailing list