map kinds of Ranges

bearophile bearophileHUGS at lycos.com
Mon May 23 16:42:03 PDT 2011


In Python you are allowed to scan a generator/iterator only once. This D code has caused me a bug:


import std.stdio, std.algorithm, std.math, std.range, std.random;
int gen(int x) { return uniform(-100, 100); }
void main() {
    auto data = map!gen(iota(10));
    writeln(data); // just a debug print
    writeln(data); // just a debug print
    int result = minPos!((a, b){ return abs(a) < abs(b); })(data).front();
    writeln(result);
}


I think gen() get called every time data() is accessed, so abs(a)<abs(b) gives bogus results.

I think the result of map() has to become a Forward Range only if the mapping function is pure (even if iota() here is more than just a Forward Range), otherwise it's better to make it a Input Range (so you can't use minPos on it, and this bug doesn't happen).

Bye,
bearophile


More information about the Digitalmars-d mailing list