I'm implementing my own programming language and getting stumped on what for loop syntax to choose.
It seems that all latest and cool languages are using the range based for loop. I googled hard in order to understand its pros and cons, the the only answer seems to be cleaner and cooler
.
While I can be cool by flowing the trend. I can't convince myself it's better than the c style for loop.
I think it is great to support shortcuts like for(:), foreach, for ... in..., but shouldn't the old c style for loop be supported as a universal fallback?
for(int i =0;i<len;++i) {}
Because it is so flexible and can easily handle all possible cases. To me, it's an example of "less is more".
With it, I don't need to search for answers like :
using range based for loop for iterating on a sub range
https://www.dotnetperls.com/range-swift
Skip 1st Iteration of Range-Based For Loops
I only need to remember one syntax to achieve everything. For example, the following snippet implements a run length encoding algorithm. You can update the index of the for loop in a sub while loop. You don't need to progress with a constant step. You don't have to pre-define the looping behavior.
// CPP program to implement run length encoding
#include <bits/stdc++.h>
using namespace std;
void printRLE(string str)
{
int n = str.length();
for (int i = 0; i < n; i++) {
// Count occurrences of current character
int count = 1;
while (i < n - 1 && str[i] == str[i + 1]) {
count++;
i++;
}
// Print character and its count
cout << str[i] << count;
}
}
int main()
{
string str = "wwwwaaadexxxxxxywww";
printRLE(str);
return 0;
}
Is the range based loop mainly for language ergonomics?
but aren't these ugly? You end up typing more to achieve the same.
for i in stride(from:5,through:1,by:-1) { print(i) } // 5 4 3 2 1
for (n, prime) in primes.enumerated() {}
Edit: After writing the initial question, I faintly remembered that swift seemed to support c style for loop at the beginning and removed it later. After googling that history, I found https://github.com/apple/swift-evolution/blob/master/proposals/0007-remove-c-style-for-loops.md , which has some of the reasoning behind it. I don't think "not very Swift-like." is very logical though ...