Decrease number of front evaluations

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Aug 26 01:59:34 PDT 2015


On 08/26/2015 01:27 AM, FreeSlave wrote:

 > I would want to avoid redundant front evaluations.

Another option is std.functional.memoize:

import std.stdio;
import std.functional;
import std.algorithm;
import std.array;

void main()
{
     auto r = [ 1, 2, 1 ]
              .map!(memoize!(delegate(int a) {
                          writefln("map for %s", a);
                          return a;
                      }))
              .filter!(memoize!(delegate(int a) {
                          writefln("filter for %s", a);
                          return a;
                      }));

     r.each;
}

Although there are two 1s, the second one is not evaluated because the 
result of the first one is used:

map for 1
filter for 1
map for 2
filter for 2

Ali



More information about the Digitalmars-d-learn mailing list