To lessen the function pointers/delegates distinction

bearophile bearophileHUGS at lycos.com
Mon Mar 4 18:36:44 PST 2013


I am thinking about one enhancement request, but I am not sure if 
the idea is meaningful, so I show it here first.

The presence of both function pointers and delegates makes the 
usage of higher order functions harder in D compared to function 
languages.

So maybe it's possible to support this code in D:

int foo(int x) { return x; }
void bar(int delegate(int) dg) {}
void main() {
     bar(&foo);
}


DMD 2.063alpha gives:

temp.d(4): Error: function temp.bar (int delegate(int) dg) is not 
callable using argument types (int function(int x))
temp.d(4): Error: cannot implicitly convert expression (& foo) of 
type int function(int x) to int delegate(int)



If you don't like implicit casts, then a possible alternative 
syntax:

int foo(int x) { return x; }
void bar(int delegate(int) dg) {}
void main() {
     bar(cast(delegate)&foo);
}

- - - - - - - - - -

An usage example where the difference between function pointers 
and delegates makes things much harder than necessary:


import std.stdio, std.algorithm;
T delegate(S) compose(T, U, S)(immutable T delegate(U) f,
                                immutable U delegate(S) g) {
     return s => f(g(s));
}
void main() {
     int delegate(int)[] functions = [x => x * 3,
                                      x => x * x,
                                      x => x + 2];
     auto allFunctions = functions.reduce!compose;
     allFunctions(5).writeln;
}


This works, but if you try to change that code a little, the 
compilation will fail in a surprisingly large variety of cases.

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list