Cartesian product of two or more lists: Difference between revisions
Content added Content deleted
m (→Functional JS) |
(→Functional JS: Updated n-ary version.) |
||
Line 1,162: | Line 1,162: | ||
For the n-ary Cartesian product over a list of lists: |
For the n-ary Cartesian product over a list of lists: |
||
<lang JavaScript>(() => { |
<lang JavaScript>(() => { |
||
⚫ | |||
// n-ary Cartesian product of a list of lists |
// n-ary Cartesian product of a list of lists. |
||
// cartProdN :: [[a]] -> [[a]] |
// cartProdN :: [[a]] -> [[a]] |
||
const cartProdN = |
const cartProdN = foldr( |
||
xs => as => |
|||
bind(as)( |
|||
x => bind(xs)( |
|||
a => [[a].concat(x)] |
|||
⚫ | |||
⚫ | |||
⚫ | |||
// |
// TEST ------------------------------------------- |
||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
[50, 100] |
|||
⚫ | |||
show(cartProdN([ |
|||
[1, 2, 3], |
|||
[], |
|||
[50, 100] |
|||
])) |
|||
⚫ | |||
}; |
|||
⚫ | |||
// bind :: [a] -> (a -> [b]) -> [b] |
// bind :: [a] -> (a -> [b]) -> [b] |
||
const bind = |
const bind = xs => f => xs.flatMap(f); |
||
// foldr (a -> b -> b) -> b -> [a] -> b |
// foldr :: (a -> b -> b) -> b -> [a] -> b |
||
const foldr = |
const foldr = f => a => xs => { |
||
let v = a, |
|||
i = xs.length; |
|||
while (i--) v = f(xs[i])(v); |
|||
return v; |
|||
}; |
|||
// intercalate :: String -> [a] -> String |
// intercalate :: String -> [a] -> String |
||
const intercalate = |
const intercalate = s => xs => xs.join(s); |
||
// map :: (a -> b) -> [a] -> [b] |
// map :: (a -> b) -> [a] -> [b] |
||
const map = |
const map = f => xs => xs.map(f); |
||
// show :: a -> String |
// show :: a -> String |
||
const show = x => JSON.stringify(x); |
const show = x => JSON.stringify(x); |
||
return main(); |
|||
// unlines :: [String] -> String |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
})();</lang> |
})();</lang> |
||
{{Out}} |
{{Out}} |