A couple of additions to Data.Bits
Population count is an often-needed function when bitfiddling, so I think a version should be supplied. I also have included functions for converting to and from lists of Booleans:
-- population count
popCount :: (Bits a, Num t) => a -> t
popCount x = count' (bitSize x) x 0
where
count' 0 _ acc = acc
count' n x acc = count' (n-1) (x `shiftR` 1) (acc + if x .&. 1 == 1 then 1 else 0)
-- this weird if/else is to preserve the nice type signature :)
-- converts a list of bools to a number
fromBools :: (Bits a) => [Bool] -> a
fromBools = foldl' (\i b -> (i `shiftL` 1) .|. if b then 1 else 0) 0 -- likewise
-- converts a number to a list of bools
toBools :: (Bits a) => a -> [Bool]
toBools x = reverse (toBools' (bitSize x) x)
where
toBools' 0 _ = []
toBools' n x = (x .&. 1 == 1) : toBools' (n-1) (x `shiftR` 1)
Trac metadata
| Trac field | Value |
|---|---|
| Version | 6.11 |
| Type | Bug |
| TypeOfFailure | OtherFailure |
| Priority | normal |
| Resolution | Unresolved |
| Component | libraries/base |
| Test case | |
| Differential revisions | |
| BlockedBy | |
| Related | |
| Blocking | |
| CC | |
| Operating system | |
| Architecture |