Ultra-pure map()?
John Colvin
john.loughran.colvin at gmail.com
Fri Dec 27 17:54:26 PST 2013
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.
More information about the Digitalmars-d-learn
mailing list