map kinds of Ranges

Jonathan M Davis jmdavisProg at gmx.com
Mon May 23 19:33:36 PDT 2011


On 2011-05-23 19:05, Andrei Alexandrescu wrote:
> 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.

Setting aside this particular issue with purity, I would very much like to see 
conditional purity implemented (along with conditional nothrow, conditional 
@safe, etc.), or it's going to be next to impossible to have stuff like map be 
pure even when it should be able to. I think that conditional attributes for 
templated functions would _really_ help make attributes such as pure and 
nothrow properly useable. I'm not sure that they'll ever truly be useful in 
the general case without conditional attribututes. I keep trying to write 
range-based code which uses pure and nothrow, and it often just doesn't work. 
Conditional attributes would fix that. I know that it's been discussed before, 
but I'd _really_ love to see it actually implemented instead of just 
discussed. Unfortunately, I have plenty of other stuff to do other than trying 
to learn the compiler well enough to attempt to implement such a feature 
myself.

Regardless, I agree that enforcing extra conditions based on purity for map 
would not be good. It would be _far_ too constrictive. You just have to be 
smart about what functions you give it. If we try too hard to stop people from 
creating bugs, we'll lose a lot of D's power and elegance.

- Jonathan M Davis


More information about the Digitalmars-d mailing list