by mrcartmenez · 5y ago · 0 comments
A for loop can implement a reduce, a reduce can implement a map, a map can implement a forEach, but not the inverse.
In [1]: def lred(function, iterable, initializer):
...: acc = initializer
...: def reductor(el):
...: nonlocal acc
...: acc = function(acc, el)
...: for n in map(reductor, iterable): pass
...: return acc
...:
In [2]: lred(lambda a,b: 10*a + b, [2,4,6,3,1], 40)
Out[2]: 4024631
What's stopping you from running these equivalencies in either direction?A map can run code per list element but the result must be injective (one-to-one).
Reduce can do all of the above, but must return a lower dimension result from its input.
And finally, a for loop is basically omnipotent.
acc = []
for el in values:
acc.append(f(el))
return acc
This hierarchy doesn't exist; you can pretty much implement any of them in terms of the others.To make that untrue, you need to define very strict limits on what else your language can do.
(Sure, we produce a transformed list here through the use of side effects. But note that the original example sparking the claim that forEach can't do what map can was this:
.forEach(() => button.click())
Side effects are clearly allowed.)You can implement any of them in terms of the others, but only if you break convention and introduce side effects. Follow convention and try to implement (for example) reduce with map and you'll find that it's not possible.
And without side-effects, a map can't implement a forEach.
What do you mean by this? You can accumulate just about anything into the resulting object, including a copy of the original array.
Of course, in fact you could hack anything in any of these, since you could be doing other work in the function called. But I think the general principle is sound.
You might notice this problem above, where it's necessary to do
for n in map(reductor, iterable): pass
to realize the mapping.So can map. Ditto.
So can foreach. Ditto again.
for el in values:
if el == 3: pass
else:
do_something_with( el )