I want to write a functional equivalent of the list comprehensions using higher-order functions only and without side effects. I do this for strictly learning purposes. I know that list comprehensions are Pythonic. In Python map(f, xs)
is equivalent to [f(x) for x in xs]
. But what are the equivalents of these below?
- A:
[f(x, y) for x in xs for y in ys]
- B:
[f(x, y) for x in range(1, 5) for y in range(x, 5)]
map
only returns lists of the same length. reduce
is more general, you can implement map
and filter
upon it.
map(f, xs) == reduce(lambda a, e: a + [f(e)], xs, [])
filter(p, xs) == reduce(lambda a, e: a + [e] if p(e) else a, xs, [])
Therefore A can be implemented as:
def map2(f, xs, ys):
reduce(lambda a, x: a + map(lambda y: f(x, y), ys), xs, [])
But this doesn't generalize to >2 for clauses. And B is even more tricky, as the iteration variable from 1st for clause is used in the 2nd clause. How do i write a function (or set of functions) that implement list comprehension functionality?