Map Lambda with Side-Effects

"Nordlöw" via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Jan 13 12:38:08 PST 2015


On Tuesday, 13 January 2015 at 07:35:53 UTC, Nordlöw wrote:
> Somewhat related to
>
> https://github.com/D-Programming-Language/phobos/pull/2024
>
> I wonder about the soundness of `map` in
>
>
> ```D
> import std.algorithm, std.range, std.stdio;
> void main(string[] args)
> {
>       long[] arr;
>       const n = 3;
>       iota(n).map!(a => arr ~= a);
>       writeln(arr);
>       writeln(iota(n).map!(a => arr ~= a));
>       writeln(arr);
> }
> ```
>
> that prints
>
> ```D
> []
> [[0], [0, 1], [0, 1, 2]]
> [0, 1, 2]
> ```
>
> Shouldn't a warning at least be issued for return-ignoring calls
> to map with mutating lambdas? Has there been any discussions on
> making map require pure functions now that we have each? I guess
> a new function, say `mapPure`, may be neccessary as adding such 
> a
> restriction to the lambda will break too much code right?

To clarify:

I f() is stronly pure function then DMD since 2.066 will warn 
about

    f();

, that is, upon return-discarding calls to strongly pure function.

I believe

     iota(n).map!(a => arr ~= a);

is a very similar mistake done and if possible should be warned 
about.

Is it possible to
- detect that a lambda is has-side-effects and that
- the map hasn't been used?

If this can't (yet) be detected in compiled-time what about 
issuing an exception in the destructor of Map to detect this?

Destroy!


More information about the Digitalmars-d-learn mailing list