Cartesian product of two or more lists: Difference between revisions

Content added Content deleted
(→‎Functional JS: Reformulated in terms of Array.flatMap)
Line 1,092:
For the Cartesian product of just two lists:
<lang JavaScript>(() => {
 
// CARTESIAN PRODUCT OF TWO LISTS -----------------------------------------
 
// cartProd :: [a] -> [b] -> [[a, b]]
const cartProd = (xs, => ys) =>
concatMap(xs.flatMap(x => concatMapys.map(y => [x, y]))
[x, y]
], ys)), xs);
 
 
// GENERIC FUNCTIONS ------------------------------------------------------
 
// concatMap :: (a -> [b]) -> [a] -> [b]
const concatMap = (f, xs) => [].concat.apply([], xs.map(f));
 
// map :: (a -> b) -> [a] -> [b]
const map = (f, xs) => xs.map(f);
 
// show :: a -> String
const show = x => JSON.stringify(x); //, null, 2);
 
// unlines :: [String] -> String
const unlines = xs => xs.join('\n');
 
// TEST -------------------------------------------------------------------
return unlines(map(show, [
cartProd([1, 2], )([3, 4]),
cartProd([3, 4], )([1, 2]),
cartProd([1, 2], )([]),
cartProd([], )([1, 2]),
].map(JSON.stringify).join('\n');
})();</lang>
{{Out}}