[Proposal] Loops: improve first-item-is-special scenario
See original GitHub issueProblem
I can’t count the times when I had to write something like
var first = true;
foreach (var x in xs) {
if (!first) {
builder.Append(",");
}
else {
first = false;
}
...
}
Not only is this verbose, but also inefficient – each iteration checks the variable even though it is known in advance it would be false for all but the first.
Potential solutions
A. Provide a first {} block.
Example:
foreach (var x in xs) {
first {} else {
Append(",");
}
...
}
Pros:
- Reduced verbosity
- Potential for compiler optimizations by separating first item handling from the remaining loop
Cons:
- No idea for good not-first syntax:
first {} else {}
,!first {}
?
B. Provide an automatic loop index variable in loops.
Example:
foreach (var x in xs) {
if (index > 0) { // "index" is automatically provided here
Append(",");
}
...
}
Pros:
- Reduced verbosity
- An index that might be useful for other things such as numbering in output
Cons:
- Compiler optimizer would have to look for specific coding patterns (
if (index > 0)
) if it wants to make the loop more efficient.
Issue Analytics
- State:
- Created 9 years ago
- Comments:36 (15 by maintainers)
Top Results From Across the Web
[1805.03374] A Proposal for Loop-Transformation Pragmas
We propose additional pragmas for common loop transformations that go far beyond the transformations today's compilers provide and should ...
Read more >Proposal: Multi-object `for` loops · Issue #7257 · ziglang/zig
Say I have some large arrays of the same size, and I want to perform some element-wise operation on them. In status quo,...
Read more >RFP # 2023-06: Engineering Service- Outer Loop Water ...
This request for proposal (RFP) for the City of Dallas, Georgia – Outer Loop Water System Upgrade Project – Phase I (Project) invites...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
… in which case you can still use the indexed signature of the Select extension, write your own extension or simply convert to a in-memory representation, which is better when handling data in multi-threaded environments anyway.
Still, there is no need for this feature, as some kind of bool evaluation has inevitably to be made and there are many ways to reduce verbosity here short of changing the language.