map/filter/reduce: use functions or delegates or both?

Falk Henrich schreibmalwieder at hammerfort.de
Thu Mar 15 16:16:51 PDT 2007


Hi!

I just started learning D. I really like D's combination of high- and
low-level features. Hence, I started coding map/filter/reduce as known from
functional languages for dynamic array types. Using anonymous delegates one
can compute the sum of the squares of an integer array like

int[] b = reduce( (int x, int y) { return x + y; }, 0, map ( (int x)
{ return x*x; }, a));

given a definition of map as (my newbee code)

To[] map(From, To)(To delegate(From) f, From[] a)
{
  To[] b;
  b.length = a.length;
  for(int i = 0; i < a.length; i++) {
    b[i] = f(a[i]);
  }
  return(b);
}

and reduce as (my newbee code)

B reduce(A,B) ( B delegate(A,B) f, B e, A[] a)
{
  foreach(A x; a) {
    e = f(x,e);
  }
  return(e);
}

Now I tried to improve the readability of the functionals by defining

int plus(int x, int y) { return x + y; }
int square(int x) { return x * x; }

in order to write

int[] b = reduce(plus, 0, map(square, a));

But this won't work since plus and square are functions and delegates.
Therefore, I replaced "delegate" by "function" in the definitions above.
But this breaks the application using anonymous delegates. Neither is it
possible to have a delegate map together with a function map in the same
module.

Is there any solution to this dilemma?

Thanks for advice.

Falk



More information about the Digitalmars-d-learn mailing list