March 22
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.

March 22

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.