Cartesian product of two or more lists: Difference between revisions
Cartesian product of two or more lists (view source)
Revision as of 12:33, 18 September 2019
, 4 years ago→Functional JS: Updated n-ary version.
m (→Functional JS) |
(→Functional JS: Updated n-ary version.) |
||
Line 1,162:
For the n-ary Cartesian product over a list of lists:
<lang JavaScript>(() => {
// n-ary Cartesian product of a list of lists.
// cartProdN :: [[a]] -> [[a]]
const cartProdN =
//
[1776, 1789],▼
[4, 14, 23],▼
show(cartProdN([▼
[50, 100]
])),▼
show(cartProdN([
[1, 2, 3],
[],
[50, 100]
]))
])▼
};
// bind :: [a] -> (a -> [b]) -> [b]
const bind =
// foldr :: (a -> b -> b) -> b -> [a] -> b
const foldr =
let v = a,
i = xs.length;
while (i--) v = f(xs[i])(v);
return v;
};
// intercalate :: String -> [a] -> String
const intercalate =
// map :: (a -> b) -> [a] -> [b]
const map =
// show :: a -> String
const show = x => JSON.stringify(x);
return main();
▲ const unlines = xs => xs.join('\n');
▲ // TEST -------------------------------------------------------------------
▲ return intercalate('\n\n', [unlines(map(show, cartProdN([
▲ [1776, 1789],
▲ [7, 12],
▲ [4, 14, 23],
▲ [0, 1]
▲ ]))),
▲ show(cartProdN([
▲ [1, 2, 3],
▲ [30],
▲ [50, 100]
▲ ])),
▲ show(cartProdN([
▲ [1, 2, 3],
▲ [],
▲ [50, 100]
▲ ]))
▲ ])
})();</lang>
{{Out}}
|