Operators as function arguments?

Daniel Keep daniel.keep.lists at gmail.com
Fri Mar 23 17:07:18 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

Like Chris said, there's really no way to get what you want in this
case.  D is not Haskell, so we just have to make lots of delegates :P

Way back when I first started using D, I actually wrote up a bunch of
templates that defined delegates for every unary and binary operator,
and a bunch of templated tests (like less-than, equal-to, etc.).

Re: your cat template above, you should be able to do this:

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

Which saves you from having to define the alias.

Also as Chris said, macros may save the day, but they will likely be a
while in coming: D2.0 is looking bigger and bigger every day :P

The way I look at functional programming in D is basically: It's not as
good as a *real* functional programming language, but boy does it beat
the pants off C/C++/Java/C#/etc.!

Anyway, hope this helps some.

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

Oh, you have no idea how much of a kick it is to see that link.  ^_^

	-- 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/


More information about the Digitalmars-d-learn mailing list