[Issue 5550] std.range.enumerate()
d-bugmail at puremagic.com
d-bugmail at puremagic.com
Mon Mar 26 15:39:49 PDT 2012
http://d.puremagic.com/issues/show_bug.cgi?id=5550
--- Comment #1 from bearophile_hugs at eml.cc 2012-03-26 15:40:12 PDT ---
This is a basic implementation of enumerate() (it's only an InputRange, but
probably a richer range too should be supported).
The demo code in main() shows the task of processing the Sieve of Eratosthenes
flags without and with an enumerate(). The version with enumerate() is shorter
and simpler to understand than the version with zip.
import std.stdio, std.algorithm, std.range, std.typecons, std.traits,
std.array;
struct Enumerate(R) {
R r;
int i;
alias r this;
@property Tuple!(typeof(this.i), typeof(R.init.front)) front() {
return typeof(return)(i, this.r.front);
}
void popFront() {
this.r.popFront();
this.i++;
}
}
Enumerate!R enumerate(R)(R range, int start=0) if (isInputRange!R) {
return Enumerate!R(range, start);
}
void main() {
// not prime flags, from a Sieve of Eratosthenes.
// 0 = prime number, 1 = not prime number. starts from index 2.
auto flags = [0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1];
// not using enumerate
iota(2, int.max).zip(flags).filter!q{!a[1]}().map!q{a[0]}().writeln();
iota(int.max).zip(flags).filter!q{!a[1]}().map!q{a[0] + 2}().writeln();
// using enumerate
//flags.enumerate(2).filter!q{!a[1]}().map!q{a[0]}().writeln(); // error
filter!q{!a[1]}(flags.enumerate(2)).map!q{a[0]}().writeln();
}
Note: this produces a compilation error, I don't know why yet, maybe it's a bad
interaction with alias this:
flags.enumerate(2).filter!q{!a[1]}().map!q{a[0]}().writeln();
--
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------
More information about the Digitalmars-d-bugs
mailing list