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 = |
const cartProd = xs => ys => |
||
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 |
return [ |
||
cartProd([1, 2] |
cartProd([1, 2])([3, 4]), |
||
cartProd([3, 4] |
cartProd([3, 4])([1, 2]), |
||
cartProd([1, 2] |
cartProd([1, 2])([]), |
||
cartProd([] |
cartProd([])([1, 2]), |
||
])); |
].map(JSON.stringify).join('\n'); |
||
})();</lang> |
})();</lang> |
||
{{Out}} |
{{Out}} |