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: Line 1,092:
For the Cartesian product of just two lists:
For the Cartesian product of just two lists:
<lang JavaScript>(() => {
<lang JavaScript>(() => {

// CARTESIAN PRODUCT OF TWO LISTS -----------------------------------------
// CARTESIAN PRODUCT OF TWO LISTS -----------------------------------------


// cartProd :: [a] -> [b] -> [[a, b]]
// cartProd :: [a] -> [b] -> [[a, b]]
const cartProd = (xs, ys) =>
const cartProd = xs => ys =>
concatMap((x => concatMap(y => [
xs.flatMap(x => ys.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 -------------------------------------------------------------------
// TEST -------------------------------------------------------------------
return unlines(map(show, [
return [
cartProd([1, 2], [3, 4]),
cartProd([1, 2])([3, 4]),
cartProd([3, 4], [1, 2]),
cartProd([3, 4])([1, 2]),
cartProd([1, 2], []),
cartProd([1, 2])([]),
cartProd([], [1, 2]),
cartProd([])([1, 2]),
]));
].map(JSON.stringify).join('\n');
})();</lang>
})();</lang>
{{Out}}
{{Out}}