Search code examples
c#delegatesfunctional-programming

Is there a use for a delegate type that returns a delegate of the same type as itself?


I was fiddling around in Visual Studio and I discovered that

delegate RecursiveDelegate RecursiveDelegate();

is a valid delegate definition.

I don't have a great deal of functional programming experience, but I was wondering if this pattern is ever actually useful in functional programming, or if its just a curiosity of semantics. I want to ask this question in two ways:

  1. In a context with side effects. I can see this actually being a half-way decent way to model iteratively learning algorithms in a functional language, where the actual task of the algorithm is performed as a side effect, and the new version of the function is the return value. Is this done?
  2. In a context without side effects. I think that this in principle useless, but I'm super curious if I'm wrong. Can this be useful if we assume that the implementation of RecursiveDelegate() has no side effects?

Solution

  • It's a potentially useful pattern for a state machine:

    delegate State State();
    
    State state = MainMenu;
    
    while (state != null) // or have a 'pump' call each update
    {
       state = state();
    }
    
    State MainMenu()
    {
       if (playPressed) return StartLevelOne();
       return MainMenu;
    }
    
    State StartLevelOne()
    {
       //set up level
       return LevelOne;   // or LevelOne() if you want an immediate update
    }
    
    State LevelOne()
    {
        //check for level one ending
        return LevelOne;
    }