Skip to content

Instantly share code, notes, and snippets.

@ehamberg
Created January 28, 2011 09:49
Show Gist options
  • Save ehamberg/800054 to your computer and use it in GitHub Desktop.
Save ehamberg/800054 to your computer and use it in GitHub Desktop.
-- lazily produce the binary representation of a number as a list of [0,1]
bin ∷ Integer → [Integer]
bin n = bin' n ((floor ∘ logBase 2 ∘ fromIntegral) n)
where bin' 1 0 = [1]
bin' 0 0 = [0]
bin' a b = if a ≥ 2^b
then 1:bin' (a-2^b) (b-1)
else 0:bin' a (b-1)
popCount :: Integer -> Integer
popCount n = foldr (+) 0 (bin n)
main = do
print $ popCount 23
print $ popCount 48975823499389471387489274897123894718238947238947189
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment