map kinds of Ranges
Andrei Alexandrescu
SeeWebsiteForEmail at erdani.org
Mon May 23 19:05:24 PDT 2011
On 5/23/11 6:42 PM, bearophile wrote:
> 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
This amount of babysitting would be unacceptable for map. A function
can't be pure for a variety of reasons.
Andrei
More information about the Digitalmars-d
mailing list