Function sets as definable type

Xinok xinok at live.com
Sat Nov 23 10:41:21 PST 2013


I'm not exactly sure how to explain this idea, but I'll do my 
best and hopefully I don't confuse anybody...

D is one of many statically-typed languages which supports 
overloading functions by parameter type and parameter count. Many 
of these languages also support function pointers / delegates, 
but these have the limitation of only pointing to a single 
function. I've yet to encounter a language that can define a 
function pointer or delegate which points to two or more 
overloaded functions. To me, this is akin to how C handles arrays 
which requires passing pointer and length pairs as separate 
arguments.

It's possible to do this in D statically via template alias 
parameters, but not dynamically via a function argument. 
Likewise, you can't easily limit it to a subset of the function 
overloads (two or more, but not all). I'm sure somebody could 
design an elegant solution using the meta-programming abilities 
of D, but I think I have a better idea...

Consider internally, such a type would be a set of two or more 
functions / delegates. Internally, this is exactly what 
interfaces are as well.

So that's my proposal: Allow implicitly casting a set of 
overloaded functions to a compatible interface. If a function is 
passed as an argument to an interface parameter, the compiler 
will automatically generate a binding of that function to that 
interface. I used the term "compatible interface" as obviously, 
not all interfaces would work. I'd rather leave it to the 
community to define what a "compatible interface" is.

What use cases are there? Well, properties are also overloaded 
functions, one which gets the value, and one or more which sets 
the value. There are many cases in which a container doesn't 
allow handling elements as l-values, such as when opIndex and 
opIndexAssign are used, and ranges don't require .front and .back 
to be l-values. The result is that specialized functions must be 
written to handle these cases, one example being std.algorithm 
which implements a private function swapAt to handle the former 
case. I've had to do this myself, implementing a function, 
swapFront, to swap the front elements of two forward ranges.

A more complex case is how to handle opIndex and opIndexAssign. 
Not all containers implement it as an l-value, which would 
prevent such a case from working: swap(r[a], r[b]). I'm sure 
there are more complex cases as well. In these situations, it 
would be great if a property could be generated from any 
arbitrary expression.

Special standard library functions / templates could be used to 
auto-generate compatible interfaces. For example, we could define 
a template which takes the get / set types as arguments and 
generates an interface for it:
void foo(Property!(int, int) prop){ }


Thoughts?


More information about the Digitalmars-d mailing list