Thread overview
map! evaluates twice
Jun 10, 2022
Antonio
Jun 10, 2022
Ali Çehreli
Jun 16, 2022
Salih Dincer
Jun 16, 2022
Ali Çehreli
Jun 12, 2022
Antonio
June 10, 2022

When mapping and filtering, the last mapped element is evaluated twice... Is it the expected behaviour?

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

June 10, 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?

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:

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

June 10, 2022
On 6/10/22 13:47, Steven Schveighoffer wrote:

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

Others don't know but as I will likely show during a lightning talk at DConf, I am trying to finish a .cached range algorithm that caches all elements that are in use. (It must drop old elements so that an infinite range does not require infinite cache.)

It is supposed to evaluate elements only once.

Ali

June 12, 2022

On Friday, 10 June 2022 at 20:47:14 UTC, Steven Schveighoffer wrote:

>

On 6/10/22 4:33 PM, Antonio wrote:
...

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

Thank you very much, Steve

June 16, 2022

On Friday, 10 June 2022 at 22:10:10 UTC, Ali Çehreli wrote:

>

[...] I am trying to finish a .cached range algorithm that caches all elements that are in use. (It must drop old elements so that an infinite range does not require infinite cache.)

It is supposed to evaluate elements only once.

I guess the developed cached() and cache() are different things, right? I tried cached(), it works fine and cleverly designed...

SDB@79

June 16, 2022
On 6/16/22 00:58, Salih Dincer wrote:

> I guess the developed cached() and cache() are different things,
> right?

cache caches only the front element.

  https://dlang.org/library/std/algorithm/iteration/cache.html

> I tried cached()

cached() is supposed to cache as many elements as needed as long as there are ranges that still reference the elements. Technically, cached() does not exist because only a couple of people have seen a draft of it. :)

Ali