Cartesian product of two or more lists: Difference between revisions

→‎Functional JS: Updated applicative version
(→‎Functional JS: Updated applicative version)
Line 1,114:
 
 
EvenAbstracting morea economicallylittle more, we can define the cartesian product quite economically in terms of ana general applicative operator:
<lang Javascript>(() => {
 
// CARTESIAN PRODUCT OF TWO LISTS -----------------------------------------
 
// cartesianProduct :: [a] -> [b] -> [(a, b)]
const cartesianProduct = (xs, ys) =>
ap(xs.map(x => y => [x, y]Tuple), ys);
 
 
// GENERIC FUNCTIONS ------------------------------------------------------
 
// e.g. [(*2),(/2), sqrt] <*> [1,2,3]
Line 1,134:
 
// ap (<*>) :: [(a -> b)] -> [a] -> [b]
const ap = (fs, => xs) => //
// The sequential application of each of a list
fs.reduce((a, f) => a.concat(
// of functions to each of xs.reduce((a, x)list =>of avalues.concat([f(x)]), [])
), []);fs.flatMap(
f => xs.map(f)
);
 
// Tuple (,) :: a -> b -> (a, b)
// TEST -------------------------------------------------------------------
const Tuple = a => b => [a, b];
 
// TEST -------------------------------------------------------------------
return [
cartesianProduct([1, 2], )([3, 4]),
cartesianProduct([3, 4], )([1, 2]),
cartesianProduct([1, 2], )([]),
cartesianProduct([], )([1, 2]),
]
.map(JSON.stringify)
9,659

edits