question on map

Mike Parker aldacron at gmail.com
Wed May 12 10:55:09 UTC 2021


On Wednesday, 12 May 2021 at 09:52:52 UTC, Alain De Vos wrote:
> As oppposed to what i expect code below prints nothing nothing 
> on the screen. What is wrong and how to fix it ?
> ```
> import std.stdio;
> import std.range:iota;
> import std.algorithm:map;
>
> bool mywriteln(int x){
> 	writeln(x);
> 	return true;
> }
>
> void main(){
> 	5.iota.map!mywriteln;
> }
>
> ```

Berni44 and visitor are correct about the laziness, but you don't 
need to use `array` to trigger the operations. That's a needless 
allocation. `std.algorithm.each` will do the same thing, without 
the allocation. So you could do this:

```d
import std.algorithm : each, map;
5.iota.map!mywriteln.each;
```

But given a function, `each` behaves like an eager `map`, so this 
has the same result:

```d
import std.algorithm : each;
5.iota.each!mywriteln;
```


More information about the Digitalmars-d-learn mailing list