Monday, November 8, 2010

Simulate nested recursive function in C#




This topic was inspired from search keywords that hit my site. I'm wondering why the simulated nested recursive function has a problem in C#. It turns out that compilation problem for recursive lambda in C# is isolated on Microsoft C# compiler only, that wasn't the case for Mono C# compiler (or Mono does an extra mile of performing compiler magic). This works fine on Mono C# (doesn't work on Microsoft C#):

using System;

namespace Craft
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            Func<int, int> fib = n => 
            {
                if (n == 0 || n == 1)
                    return 1;
                else
                    return fib(n - 1) + fib(n - 2);
            };
            
            
            for(int i = 0; i < 10; ++i)
                Console.WriteLine ("Hello World! {0}", fib(i));
        }
        
        
    }
}



To make that work in Microsoft C#, "forward declare" the recursive lambda(e.g. Func<int, int> functionNameHere = null) before defining the lambda.

using System;

namespace Craft
{
    class Program
    {
        public static void Main (string[] args)
        {
            // forward declarations evokes C college days :-)
            Func<int, int> fib = null; 

            fib = n => 
            {
                if (n == 0 || n == 1)
                    return 1;
                else
                    return fib(n - 1) + fib(n - 2);
            };
            
            
            for(int i = 0; i < 10; ++i)
                Console.WriteLine ("Hello World! {0}", fib(i));
        }
        
        
    }
}

1 comment:

  1. Hi Mike!

    Iba ka pa rin talaga pagdating sa codes.

    Anyway, please contact me ASAP at rmoldez2k@yahoo.com (ym or email). I have programming project to show you kung kaya...

    Moldsz

    ReplyDelete