Is there a way for a function to return itself in D?

Janderson ask at me.com
Tue Oct 14 08:22:45 PDT 2008


Lars Kyllingstad wrote:
> Simen Kjaeraas wrote:
>> Like the subject says, I wonder if it's possible for a function to 
>> return itself.
>> No matter how I think of this, I end up with an endless recursive 
>> function
>> declaration. Creating a functor that does this is simple, so why not a 
>> function?
> 
> Something like this?
> 
>   import tango.io.Stdout;
> 
>   void* returnSelf()
>   {
>       Stdout("Hello world!").newline;
>       return cast(void*) &returnSelf;
>   }
> 
> Then the function can be called like this:
> 
>   void main()
>   {
>       void* function() rs;
> 
>       // This prints "Hello world!"
>       rs = cast(void* function()) returnSelf();
> 
>       // This prints "Hello world!" too.
>       rs();
>   }
> 
> But it's kinda ugly, what with the casts and all. I don't see that it is 
> useful either. It makes sense to return a functor, because it is an 
> object and has state. A function is stateless, so any "reference" to the 
> function will be identical.
> 
> -Lars

This could be useful if you are generating a stack of operations that 
can be undone (or modified).  Although in that case you could just as 
easily have a helper function that would push the function pointer and 
call the function, rather then having to add that syntax to every 
operation that goes into the stack.

-Joel


More information about the Digitalmars-d-learn mailing list