-
Notifications
You must be signed in to change notification settings - Fork 23
Add Python-style range() function and iterable #624
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
This is definitely the right place for such an extension, should we want to add it, since it creates an iterable. We've considered such "range" functions on With extensions we could possibly have both, say The implementation is not particularly efficient, unless the compiler recognizes and optimizes it. That's what worries me the most: Adding this might make people think using it is better than a normal Which prompts the question: When would you use such an iterable? So, in the currently proposed use-cases, I wouldn't actually recommend using this feature. Worst-case syntax strawman: |
If we didn't have list-comprehensions, I'd agree more. var squares = [for (var x in list) x * x]; That said, we are doing And if anything, a static method creating a known Then there is the issue that We could have Or just have It's almost like people want something smaller and without unnecessary characters. Like, native syntax for ranges! Languages with syntax for ranges exist and are happy! Python's |
Hmm. The even easier version is to make for (var i in 5) print(i); // 0, 1, 2, 3, 4 That's probably not going to fly since Anyway, maybe a getter, extension IntRange on int {
Range get range => Range(this);
}
class Range extends UnmodifiableSetBase<int> {
final int _count;
final int _offset;
Range(int count) : _count = count, _offset = 0;
Range._(this._count, this._offset);
Iterator<int> get iterator => () sync* {
for (var i = 0, delta = _count < 0 ? -1 : 1; i != _count; i += delta) yield (i + offset);
}().iterator;
bool contains(Object? n) =>
n is int && _count < 0 ? (_count < n && n <= 0) : (_count > n && n >= 0);
Range operator+(int offset) => Range._(_count, _offset + offset);
} and, voila, you can do for (var i in 5.range) { ... i is 0..4 ... }
for (var i in 5.range + 2) { ... i is 2..6 ... } Not very readable, though. |
This is very confusing to understand
Maybe |
FYI: Google has a
|
From lrhn's comment above:
I think it's probably a good thing to link dart-lang/language#3366. |
Ref: dart-lang/sdk#7775
The text was updated successfully, but these errors were encountered: