Population count: Difference between revisions
→JS ES6: Updated primitives and top-level function, wrapping object methods in directly composable functions
(Add Forth solution) |
(→JS ES6: Updated primitives and top-level function, wrapping object methods in directly composable functions) |
||
Line 927:
===ES6===
<lang JavaScript>(() => {
// popCount :: Int -> Int
const popCount = n =>
splitOn('', showIntAsBinary(n))
// GENERIC FUNCTIONS ------------------------------------------------------
// range :: Int -> Int -> [Int]▼
const range = (m, n) =>▼
// (++) :: [a] -> [a] -> [a]
const append = (xs, ys) => xs.concat(ys);
Array.from({
length: Math.floor(n - m) + 1
}, (_, i) => m + i);
// foldl :: (b -> a -> b) -> b -> [a] -> b
const foldl = (f, a, xs) => xs.reduce(f, a);
// length :: [a] -> Int
const length = xs => xs.length;
// map :: (a -> b) -> [a] -> [b]
const map = (f, xs) => xs.map(f);
// raise :: Num -> Int -> Num
const raise = Math.pow;
// showIntAsBinary :: Int -> String
const showIntAsBinary = n => n.toString(2);
// splitOn :: String -> String -> [String]
const splitOn = (cs, xs) => xs.split(cs);
// until :: (a -> Bool) -> (a -> a) -> a -> a
Line 951 ⟶ 973:
}
// TEST -------------------------------------------------------------------
// { popCounts : [Int], evenThenOdd : ([Int], [Int]) }
return {
popCounts:
evenThenOdd: until(
m => length(m.
m => ({
x: m.x + 1,
[append(m.
) : [m.
}), {
x: 0,
[],
[]
]
}
)
.evenOdd
};
})();</lang>
{{Out}}
<lang JavaScript>{"popCounts":[1, 2, 2, 4, 3, 6, 6, 5, 6, 8, 9, 13, 10, 11, 14, 15, 11, 14, 14, 17, 17, 20, 19, 22, 16, 18, 24, 30, 25, 25, 25],
|