by enriquto · 5y ago · 0 comments
Loops do not need to be artificially slow to discourage them. Any modern programming language should be able to recognize the construct and compile it in the most efficient way. Saying that you must avoid loops because they are slow is a failure in a particular programming language, not in the concept of loop. After all, all languages managed to implement loops efficiently many decades ago.
What you might write is "create a variable and set it to zero, then iterate that variable as long as it's smaller than the number of items in the array, and do this between each iteration: take the item at the variables index and set its property 'foo' to 'bar'".
Of course any programmer will instantly see what's going on, but that's not from clarity but from prior experience and familiarity.
Python, Rust, Swift, C++, ObjC and more all support the equivalent of a foreach loop today. That perfectly shows intent
In XQuery, the root type is a flattened sequence. Flattened means not just that [1, [2, 3]] is flattened to [1, 2, 3], but also the a single object 42 is equivalent to a sequence of one object [42].
This means that if I write:
declare function local:prefixName($name)
{
fn:concat("prefix-", $name)
}
I can invoke it with a single name or a sequence of names without any explicit iteration.It has drawbacks but using XQuery certainly highlights how much code we normally waste dealing with "things" and "sequences of things" separately.
(Than again working with XQuery also highlights how much code one can waste dealing with XML namespaces :)
Even with loop-over-iterable semantics, explicit loops obscure intent compared to comprehensions and map/reduce/filter/etc.; they are better than C-style loops which in turn are better than conditionals + gotos, but that doesn't make them good at expressing intent in many common cases.
if you wanted to vectorize the set/jmp version, you'd be trying to tease apart a problem which is undecidable in the limit. vectorizing the transformer version is trivial.
for item in array:
item.foo = bar array.'foo = bar
Is clearer. Or, at least, would be, if one were accustomed to the (fictitious) adverb '.There's no need for all the ceremony around specifying "for x in y: <some function describing what to do with x>"
for item in array:
item.foo = bar
for item in array:
item.foo = item.foo * 2
for item in array:
my_bar_func(item.foo)
If you special case certain uses of a for loop and add language syntax around it, of course you can make code terser. But it's nice to rely on a small set of very generally useful syntax.It's not _that_ verbose -- the trade off in clarity is pretty stark IMO.
In practice many people move between languages frequently daily. This syntax and semantics it provides are fairly different from that of popular languages.
In pandas it would be item.foo = bar, _as long as_ bar isn't something you can iterate over.
That's entirely accurate. A bag is "too expressive", in that sense. Sometimes you want to constrain the kind of container so you don't put the wrong kind of thing in there.
Another analogy: types. "Any" will let you use anything, but sometimes you want to say "only allow Integers here".
If we act like we're not actually dealing with bags at a fundamental level, we might mislead ourselves and spread the belief that the rules and labels around the bags are what matters. No, they help you (temporarily) to use the bags in a specific way in some context.
In fact, computers are extremely expressive, (bag like) things. The constraints are auxiliary. I think it's important that we keep reminding us what programming is and that it serves a direct purpose, while the bureaucracy is a support structure at best.
In addition to that, the Set is more "expressive" than the list in the right context. Or rather it expressing things more directly.
I don't think there's any _hate_ for loops, however, they are a very common pattern, so it's not unreasonable to argue it can be further refined/abstracted.
Most people agree that "for x in y: foo(x)" is an improvement over "for(int i=0; i<=n; i++) {foo(x)}". It's not wild to argue that "foo' x" is an improvement over "for x in y: foo(x)"
Well, I don't.
The second version is much clearer to me, for example, if I want to be sure about the running time of the code. Will it take one second or be instantaneous? The first example hides the length of y. I favor a programming style where all loops have clearly identifiable bounds. Using "iterators" hides these lenghts and makes the code much harder to reason about.
Clearer? Did you notice the second version contains a bug?
The first version makes it easier to spot said bug, because it's more concise and with fewer parts where you could make a mistake. Note that even in this very short piece of code it's easy to miss the bug; imagine in actual loops!
You have no guarantees about the running time of the code in either case, not without delving into the specifics of your programming language.
> I favor a programming style where all loops have clearly identifiable bounds. Using "iterators" hides these lenghts and makes the code much harder to reason about.
I find the opposite to be the case. Explicit loops with indexes make off-by-one errors likely, which is one of the most common kinds of error. It's impossible to make that kind of mistake with a foreach or map-over-this operation.
Whoops - in my defence, I haven't coded in C in a very long time. I'll leave it there, since I think it makes an (unwittingly) good point.
On the other hand, code that hides things tends to be much harder to debug, when it invariably fails. Why is my program suddenly gobbling 10GB of memory? After several hours of profiling and debugging: ah, here's this particular combination of constructors that allocates and frees a stupid amount of memory for no reason.
It has the same problem either way. Similarly, if you always know the size of n in the C style loop, then you would always know the size of y in the Python style loop.
The Python loop just has the benefit of being shorter (by a line and a few tokens).
Not a compulsory tool, not a forbidden tool, not a foolish tool, not obviously the correct tool in all situations, possibly not something that needs to be mainstream in every work flow? Sure, all of those. But ... we're downvoting loops now?
When order does matter, loops are quite enjoyable
Especially generator-to-generator combinators ie. [0] gives terse, transducer expressiveness over computation on finite/infinite streams, arrays, etc. (all iterables). It's easy to compose, jump into/out-of for-loops if needed for arbitrary yielding (ie. conditionally yielding multiple items, skipping some, halting etc); `continue`, `break`, nesting, yield, yield from (yield*), normal code in for-loops is very intuitive and terse, creating pleasant, understandable code.
Recently I had a chance to break down complex pipeline in finance project into small steps as generator-to-generator transducer functions (can you call generator-to-generator functor a trasducer?), higher order for steps that require extra inputs, leaving all pipeline pure and easy to reason about. Typescript was really helpful doing hard work where each step somehow modifies the input - leaving final result typechecked together with spotting bugs in intermediate steps ie. on their dependendency etc. really nice stuff.
Well, for me, because, compared to other notation, they usually obscure intent.
> Loops are just a nice notation for some computational constructs.
But... they're mostly not.
> Loops are just a nice notation for some computational constructs.
Sometimes, but even then if a language has decent abstraction features that’s usually best for the low-level implementation of a generic algorithm, which you should never have to see when actually applying the algorithm to concrete types. True, if you don't have a generic implementation available, YAGNI often argues in favor of a concrete one for the immediate use case, so generic implementations separated from immediate concrete use isn't the only place to use explicit loops.
Reconstructing what was meant at high level from arbitrary loops is surely intractable, but could only be a property of a compiler, not a language. Should a compiler like GCC necessarily recognize a matmul loop nest and replace it with a GEMM call? XL always does -- which can make investigating it's optimization annoying -- but then it doesn't actually recognize GEMM.
So it is not “loopless” per se, as the sigma notation for summation indicates a loop in a single construct, and it “can be written away” using Einstein’s notation.
That is how it should be understood, imo.