Ultra-pure map()?

Marco Leise Marco.Leise at gmx.de
Fri Dec 27 19:32:26 PST 2013


Am Sat, 28 Dec 2013 01:54:26 +0000
schrieb "John Colvin" <john.loughran.colvin at gmail.com>:

> On Saturday, 28 December 2013 at 01:41:35 UTC, David Held wrote:
> > import std.algorithm;
> > import std.stdio;
> > import std.conv;
> >
> > class Trivial
> > {
> >     int sideEffect() { return n++; }
> >     override string toString() pure { return to!string(n); }
> >     int n;
> > }
> >
> > void main()
> > {
> >     Trivial[] objs = [ new Trivial ];
> >     map!(o => o.sideEffect())(objs);
> >     writeln(objs);	// [0]
> >     foreach (o; objs) o.sideEffect();
> >     writeln(objs);	// [1]
> > }
> >
> > Can someone explain to me why map() is not equivalent to 
> > foreach in the code above?  From what I can tell, map() doesn't 
> > do anything at all on objs, even though it is a perfectly 
> > legitimate range (as far as I can tell).
> >
> > Dave
> 
> Map is lazy and is never iterated over in your code, therefore no 
> side effects.

Yeah, this is kind of unintended usage. Typically with map you
take some input range, apply some algorithm to each element,
and return a range of the results.

Side effects and altering the input object itself makes me
want to pull out my crucifix. You shall not have impurity in
your functional style code!

-- 
Marco



More information about the Digitalmars-d-learn mailing list