Donkey Patching
According to this slide show, the team behind D is thinking of incorporating an interesting addition to the language: The interchangability of a.foo(b) and foo(a, b).
This makes some interesting uses available. For instance, one could do something that looks a bit like monkey patching, adding functionality to library classes.
real round_to(real n, uint d) { real b = 10; real k = pow(b, d); return round(n*k)/k; }
With the proposed change I could use the round_to function like this:
real a = 9.4334566; real b = a.round_to(2); // => 9.43
I would also be able to do this:
int next(int a) { return a + 1; } int b = 3.next; // => 4
And while we’re at it:
void times(int n, void delegate() dg) { while(n\-\- > 0) { dg(); } } 5.times({ writefln("Look at me. I'm Ruby!"); });
Of course this isn’t really monkey patching. The functions doesn’t actually become a part of the class, and thus cannot use polymorphism or access private members. In all respect this is just syntactic sugar, but I like it. It gives you the illusion of having a dynamic language.
I haven’t seen this particular feature in any other language before. Does it exist elsewhere? Does it have a name? If not, I think Donkey Patching would be a suitable one.
Cheers! 🙂
The SuperCollider programming language allows writing a.f(b) also as f(a, b) since 1996.
http://supercollider.sourceforge.net/
This is also possible in Nice. http://nice.sourceforge.net/
They call them external methods.
I think there is something in C# 3.0 that looks something like this. I think they use the term Extension methouds
SuperCollider and Nice, eh? Sounds like languages I have to take a look at. I’ll put them on my got-to-learn-list, right after Lua.
External methods or Extension methods are both good names for the feature, but what should we call this limited form of monkey patching that becomes possible with it?
Also, I hope the name I suggested isn’t also the name of some dirty exercise, like these comments suggests: http://programming.reddit.com/info/2p3jm/comments
If that’s the case, I beg your apologies. English is not my native language (no kidding, right? 😉 )