[Haskell-beginners] Convert bits to bytes
Daniel Fischer
daniel.is.fischer at web.de
Thu Sep 2 13:44:44 EDT 2010
On Thursday 02 September 2010 19:29:23, Alec Benzer wrote:
> I came up with this (dealing with non-multiple of 8 numbers of bits)
>
> bitsToBytes :: [Bool] -> [Word8]
> bitsToBytes [] = []
> bitsToBytes bits = map bitsToByte (getChunks bits)
> where bitsToByte = foldl' (\byte bit -> byte*2 + if bit then 1 else 0)
> 0
>
> getChunks :: [Bool] -> [[Bool]]
> getChunks [] = []
> getChunks xs
> | length xs < 8 = getChunks $ take 8 (xs ++ repeat False)
Pet peeve.
Don't use `length xs < k' (or <=, ==, >=, >).
That fails hard on infinite lists, also it is slow and prone to cause a
space leak on long lists.
Remember, length must walk the entire list.
Instead of length xs < k use null (drop (k-1) xs), other combinations of
not, null and drop for the other tests.
Or you can use lazy Peano numbers and check
genericLength xs < (8 :: Peano).
> | otherwise =
> let (these,rest) = splitAt 8 xs
> in these:getChunks rest
More information about the Beginners
mailing list