map! evaluates twice

Steven Schveighoffer schveiguy at gmail.com
Fri Jun 10 20:47:14 UTC 2022


On 6/10/22 4:33 PM, Antonio wrote:
> When mapping and filtering, the last mapped element is evaluated 
> twice... Is it the expected behaviour?
> 
> ```d
> void main()
> {
>      import std.algorithm, std.stdio;
> 
>      [1,2,3,4,5].
>          map!((x){
>              writeln("mapping ", x);
>              return x;
>          }).
>          filter!(x=>x>2).
>          front.
>          writeln();
> }
> ```
> 
> Output
> ```
> mapping 1
> mapping 2
> mapping 3
> mapping 3
> 3
> 
> ```

`map` calls the lambda for each call to `front`. If you want a cached 
version, use `cache`:

```d
void main()
{
     import std.algorithm, std.stdio;

     [1,2,3,4,5].
         map!((x){
             writeln("mapping ", x);
             return x;
         }).
         cache.
         filter!(x=>x>2).
         front.
         writeln();
}
```

-Steve


More information about the Digitalmars-d-learn mailing list