by notJim · 5y ago · 0 comments
Guessing it's bc one-liners are easier to write than for loops in the console.
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.)What do you mean by this? You can accumulate just about anything into the resulting object, including a copy of the original array.
Firefox has a pretty good multi-line editor now if anyone was looking for that