Self function
bearophile
bearophileHUGS at lycos.com
Mon May 4 12:52:56 PDT 2009
Sometimes I rename recursive functions, or I duplicate and modify them, and they stop working because inside them there's one or more copy of their old name, so for example they recurse to their old name.
So inside a function I'd like to have a standard name to call the function itself, useful for recursivity.
(If you have two or more recursive functions that call each other this idea can't be used, but I think such situations are uncommon enough to not deserve help from the language).
I have just discussed this in the Python newsgroup too:
http://groups.google.com/group/comp.lang.python/browse_thread/thread/d265da85d4b70eaf#
I use more recursivity in D than in Python, because Python has troubles with it.
In future in D2 you may use:
int ANUGLYNAME(int n) {
if (n <= 1)
return 1;
else
mixin(__FUNCTION__ ~ "(n - 1) * n");
}
But you can't use __FUNCTION__ into a delegate/function pointer/lambda because the name isn't available, and it's a bit ugly syntax anyway...
This looks a bit better:
int ANUGLYNAME(int n) {
if (n <= 1)
return 1;
else
__self(n - 1) * n;
}
Other syntaxes are possible.
__self is a way to denote the pointer/delegate of the function currently being run, so I think the compiler is always able to that, for delegate/ function pointers/ lambdas/ methods/ virtual methods/ opCalls too.
Bye,
bearophile
More information about the Digitalmars-d
mailing list