www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - map/filter/reduce: use functions or delegates or both?

reply Falk Henrich <schreibmalwieder hammerfort.de> writes:
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
Mar 15 2007
next sibling parent Daniel Keep <daniel.keep.lists gmail.com> writes:
Falk Henrich Wrote:

 Hi!
 
 ...
 
 Is there any solution to this dilemma?
 
 Thanks for advice.
 
 Falk

I implemented these a while back using rather a lot of templates :) You can see the implementation here: http://www.prowiki.org/wiki4d/wiki.cgi?DanielKeep/functools Basically I solved the problem by using neither delegates or functions. Instead, I just used a template type called "tOp". Hope this helps :) -- Daniel
Mar 15 2007
prev sibling parent reply Denton Cockburn <diboss hotmail.com> writes:
I don't see the template functions being instantiated.
e.g. int[] b = reduce!(int, int)(plus, 0, map(square, a));

but I just started learning D too.
Mar 21 2007
parent reply Denton Cockburn <diboss hotmail.com> writes:
oh yeah, map would need to be instantiated as well.

int[] b = reduce!(int, int)(plus, 0, map!(int, int)(square, a));
Mar 21 2007
parent Daniel Keep <daniel.keep.lists gmail.com> writes:
Denton Cockburn wrote:
 oh yeah, map would need to be instantiated as well.
 
 int[] b = reduce!(int, int)(plus, 0, map!(int, int)(square, a));

D has implicit function template instantiation.
 T first(T)(T[] arr)
 {
     return arr[0];
 }

 auto one = first([1,2,3]);

-- Daniel -- int getRandomNumber() { return 4; // chosen by fair dice roll. // guaranteed to be random. } http://xkcd.com/ v2sw5+8Yhw5ln4+5pr6OFPma8u6+7Lw4Tm6+7l6+7D i28a2Xs3MSr2e4/6+7t4TNSMb6HTOp5en5g6RAHCP http://hackerkey.com/
Mar 21 2007