www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Unexpected inefficiency of minIndex

reply Alexibu <alex sunopti.com> writes:
```d
import std.stdio;
import std.algorithm;

int potentiallyExpensiveCalculation(int arg)
{
	writefln("eval %s",arg);
	return arg;
}

int[] args = [1,2,3,-1,2];
auto best = args.map!(a => 
potentiallyExpensiveCalculation(a)).minIndex;
```
This needs n-1 compares, but is also computing 
potentiallyExpensiveCalculation twice as many times as necessary.

Why does map not fully resolve to the results before it is passed 
to minIndex, so that two ints are compared not two 
potentiallyExpensiveCalculation of ints.

I didn't know map was lazy...
I could put .array between map and minIndex but that defeats the 
purpose of ranges.
Mar 22
parent Alexibu <alex sunopti.com> writes:
On Friday, 22 March 2024 at 07:18:01 UTC, Alexibu wrote:
 I didn't know map was lazy...
 I could put .array between map and minIndex but that defeats 
 the purpose of ranges.
OK found the cache algorithm, that does this.
Mar 22