Cartesian product of two or more lists: Difference between revisions
Content added Content deleted
(→{{header|Python}}: Replaced original with a function wrapper around itertools.product) |
(→{{header|Python}}: Remove non-idiomatic, convoluted, " general applicative function" version.) |
||
Line 2,105: | Line 2,105: | ||
[] |
[] |
||
</pre> |
</pre> |
||
and we could define our own '''cartesianProduct''', in terms of a general applicative function: |
|||
<lang python>from functools import (reduce) |
|||
# cartesianProduct :: [a] -> [b] -> [(a, b)] |
|||
def cartesianProduct(xs): |
|||
return lambda ys: ap( |
|||
map(lambda x: lambda y: (x, y), xs) |
|||
)(ys) |
|||
# GENERIC FUNCTIONS -------------------------------- |
|||
# apList (<*>) :: [(a -> b)] -> [a] -> [b] |
|||
def ap(fs): |
|||
return lambda xs: reduce( |
|||
lambda a, f: a + reduce( |
|||
lambda a, x: a + [f(x)], xs, [] |
|||
), fs, [] |
|||
) |
|||
# uncurry :: (a -> b -> c) -> ((a, b) -> c) |
|||
def uncurry(f): |
|||
def g(x, y): |
|||
return f(x)(y) |
|||
return g |
|||
# TEST ------------------------------------------------ |
|||
for product in map(lambda x: uncurry(cartesianProduct)(*x), ([ |
|||
([1, 2], [3, 4]), |
|||
([3, 4], [1, 2]), |
|||
([1, 2], []), |
|||
([], [1, 2]) |
|||
])): |
|||
print (product)</lang> |
|||
{{Out}} |
|||
<pre>[(1, 3), (1, 4), (2, 3), (2, 4)] |
|||
[(3, 1), (3, 2), (4, 1), (4, 2)] |
|||
[] |
|||
[]</pre> |
|||
=={{header|R}}== |
=={{header|R}}== |