Population count: Difference between revisions
Content added Content deleted
Not a robot (talk | contribs) (Add BCPL) |
m (→{{header|Haskell}}: Tidied, applied Ormolu.) |
||
Line 2,029: | Line 2,029: | ||
Or, if we want to write our own popCount, perhaps something like: |
Or, if we want to write our own popCount, perhaps something like: |
||
<lang haskell>import Data. |
<lang haskell>import Data.Bifoldable (biList) |
||
⚫ | |||
import Data.Tuple (swap) |
|||
import Data.Bool (bool) |
import Data.Bool (bool) |
||
import Data.List (partition, unfoldr) |
|||
⚫ | |||
--------------------- POPULATION COUNT ------------------- |
|||
popCount :: Int -> Int |
popCount :: Int -> Int |
||
popCount = |
popCount = sum . unfoldr go |
||
where |
|||
sum . unfoldr ((bool Nothing . Just . swap . flip quotRem 2) <*> (0 <)) |
|||
go = |
|||
( bool Nothing |
|||
. Just |
|||
. swap |
|||
. flip quotRem 2 |
|||
) |
|||
<*> (0 <) |
|||
--------------------------- TEST ------------------------- |
|||
main :: IO () |
main :: IO () |
||
main = |
main = |
||
mapM_ putStrLn $ |
mapM_ putStrLn $ |
||
zipWith |
zipWith |
||
(\k xs -> |
(\k xs -> concat [k, ":\n", show xs, "\n"]) |
||
["Population count of powers of 3", "evil", "odious"] |
["Population count of powers of 3", "evil", "odious"] |
||
((popCount . (3 ^) <$> [0 .. 29]) : |
( (popCount . (3 ^) <$> [0 .. 29]) : |
||
biList (partition (even . popCount) [0 .. 59]) |
biList (partition (even . popCount) [0 .. 59]) |
||
)</lang> |
|||
{{Out}} |
{{Out}} |
||
<pre>Population count of powers of 3: |
<pre>Population count of powers of 3: |