4 ms·
There's nothing wrong with a for-loop. Nothing at all. Using closures instead of an explicit loop is only a minor gain. The real use comes when you want to per
by lihaoyi 15y ago
There's nothing wrong with a for-loop. Nothing at all. Using closures instead of an explicit loop is only a minor gain.
The real use comes when you want to perform more complex control-flow logic with different transformations. When you are working with planar undirected graphs instead of arrays, for example a HoMM3's hexagonal grid, repeatedly writing out your breadth-first-search code to do simple graph modifications/transformations gets old really fast.
- tikhonj 15y agoWell no, there is something wrong with a for loop--it tells you the "how" rather than the "what". With a map you know it's just transforming the list with a function; with a reduce you know its combining the elements of a list with a function. With a for loop, it could be any of those, or other things besides. And it takes more code--more to read, more to think about--to encode any of them.
- lihaoyi 15y agoThat's pretty trivial though: one line of code instead of 2 or 3? Writing a for-loop to iterate over an array is so simple that Python is cutting out "reduce" entirely because for-loops aren't that bad, really. The real gain is when you are working with data structures other than arrays, then closures are 1 line rather than writing a 25 line breadth-first-traversal! If you think writing lots of for loops is tedious and confusing, try writing lots and lots of BFSs, Queue and all.
- tikhonj 15y agoWell no, it isn't trivial. It's just like using a loop instead of a goto: it makes your meaning clearer. The whole point is to make the semantics of your code easier to understand, not just to conserve lines. (Although conserving lines is also important--in my experience, a short one-line function is much easier to understand than a short three-line function.) The reason Python is cutting out reduce is that Van Rossum has an irrational antipathy towards functional programming, and that Python is really an imperative language throughout. (I know all too well as a functional programming aficionado forced to use Python.)