Self function

Georg Wrede georg.wrede at iki.fi
Mon May 4 18:55:27 PDT 2009


BCS wrote:
> Reply to Georg,
> 
>> bearophile wrote:
>>
>>> 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/lambdabecause 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.
>> Since you need this at compile time, then you don't need a pointer. A
>> name would be enough.
>>
>> If, as Denis pointed out, Andrei is going to provide that, and if it
>> turns out to have a long name (like scope.function.name), then I hope
>> it will be implemented so that you can alias that into something
>> shorter, like "thisf" or "me".
>>
> 
> 
> void main()
> {
>   int i = 0;
>   auto dg = (int j)
>   {
>       i++;
>       return j <= 1 ? 1 : self(j-1) + self(j-2);
>       // self can't be a name as the function dosn't have a name       
> // and it can't be a compile time const at the context is not known.
>   };
> 
>   dg(5);
> }

Oh boy, I missed half of the post. (Note to self: remember use two eyes 
for reading. Especially at the wee hours.)



More information about the Digitalmars-d mailing list