Operators as function arguments?
Chris Nicholson-Sauls
ibisbasenji at gmail.com
Fri Mar 23 17:38:23 PDT 2007
Falk Henrich wrote:
> 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
None, frankly. Although, with the upcoming macros feature, you might be able to do
something like this:
macro binop (Type, Op) {
(Type x, Type y) { return x Op y; }
}
b = reduce(a, binop(int[], ~));
Although, heck, you might be able to write reduce itself as a macro passing the operator
you want to it then.
macro reduce (Val, Op) {
//...
}
b = reduce(a, ~);
Which, come to think of it, is basically what you wanted in the first place!...except that
it isn't, because macros are always inlined. Best I could come up with off the top my
head, though, and reliant on as yet unreleased features.
-- Chris Nicholson-Sauls
More information about the Digitalmars-d-learn
mailing list