2

I want to write code like this:

/*something*/ Fn() { ... }

int main()
{
  /*something*/ fn = Fn;
  while(fn) fn = fn();
  return 0;
}

Is it possible to do this is a fully type safe way? Assume C, C++, D, C#, Java, or any other statically typed language.

Greg
  • 23,155
  • 11
  • 57
  • 79
BCS
  • 75,627
  • 68
  • 187
  • 294
  • It makes for a really simple DFA engine. Or with `vector`, a NFA engine – BCS Jul 01 '10 at 00:40
  • possible duplicate of [Self referential type](http://stackoverflow.com/questions/3048689/self-referential-type) BTW, the accepted answer is not the answer to your question. Look at the second answer. – David Rodríguez - dribeas Jul 01 '10 at 00:48

1 Answers1

1

Here is a C# example

delegate MyFunctionDelegate MyFunctionDelegate();

class Program
{
    static void Main(string[] args)
    {
        MyFunctionDelegate fn = FN1;
        while (fn!=null)
            fn = fn();
    }

    static MyFunctionDelegate FN1()
    {
        Console.WriteLine("FN1 called");
        MyFunctionDelegate returnDelegate = FN2;
        return returnDelegate;
    }

    static MyFunctionDelegate FN2()
    {
        Console.WriteLine("FN2 called");
        return null;
    }
}
matt-dot-net
  • 4,204
  • 21
  • 24
  • Yes, sorry I mentioned that in my orig. post and had to edit for formatting. In my opinion it's a little more straight forward in C/C++ but C# gives you strong typing. With C/C++ a pointer can point to anything and anywhere. – matt-dot-net Jul 01 '10 at 01:35