Hacker News new | ask | show | jobs
by eru 1921 days ago
Especially, a for-loop can break out early or skip elements.
1 comments

So can reduce. You'd put that logic in the function you pass to the call to reduce.

So can map. Ditto.

So can foreach. Ditto again.

  for el in values:
    if el == 3: pass
    else:
      do_something_with( el )
No, that's just a guard condition. Parent post was referring to break, i.e. skip the rest of the iteration.
For forEach that's easy:

  for el in values:
    if el == 3: return
    do_something_with( el )
For the other two, you still can, but you'll need to handle the control flow yourself, by doing something like goto or invoking a continuation.
That's a for loop. And depending on the language I'm pretty sure that return call would exit the parent scope.
> That's a for loop.

I take it you've never read any Python? That's a forEach. Python doesn't even have a for loop construct (though it does have while, which is equivalent).

> And depending on the language I'm pretty sure that return call would exit the parent scope.

Yes, that's the point, that's an illustration of terminating the forEach before you've processed each element.

I'm not very proficient in Python, no. I thought you were giving pseudo-code examples. If your argument doesn't apply to the common array methods (forEach, map, reduce) in JS and similar languages, then you missed the entire point of this comment thread.
Python's for-loops are really for-each loops.

If you have a C-style for-loop, you can and have to do everything yourself. That means you can skip elements or processer them twice, etc.

In a Python-style for-each loop, you can break out with break or return, but you have a harder time skipping or changing the order of processing. So they are weaker. And that's good.

(Your examples still process elements in the body of the loop. It's just that sometimes the body decides to do a no-op.)

Putting the no-op logic in the body of the loop, or in the function you pass to reduce is different than being able to short-cut evaluation.

You can see the difference most clearly, when trying to process (the start of) an infinite generator with reduce or a for-loop. Reduce will just hang.