Operators as function arguments?

Falk Henrich schreibmalwieder at hammerfort.de
Fri Mar 23 13:22:13 PDT 2007


Hi!

I'm trying to do some functional programming in D and came across the
following problems:

Can I somehow use the built-in operator ~ as an argument to a function? The
doc [1] seems to say no as operator overloading is implemented by adding a
non-static member function to some class.

It would avoid lots of repetitive definitions of anonymous delegates. The
following example uses reduce from [2]:

int[][] a; int[] b;
b = reduce(a, (int[] x, int[] y){return x~y;});

Now it would be useful to do

b = reduce(a,~);

It would be even nicer to define "flatten" using templates to avoid code
duplication for different types of arrays. I tried to define

T[] cat(T)(T[] a, T[] b) { return a ~ b; }

but then

b = reduce(a, &cat);

yields

cat(T) is not an lvalue

The only workaround seems to be to explicitly instantiate the template
function:

alias cat!(int) catInt;
b = reduce(a, &catInt);

But this is extremely clumsy. Any idea?

Falk


[1] http://www.digitalmars.com/d/operatoroverloading.html
[2] http://www.prowiki.org/wiki4d/wiki.cgi?DanielKeep/functools


More information about the Digitalmars-d-learn mailing list