Saturday, March 14, 2009

Lazy Evaluation : A Future CLR Need ?

Let's us first have a look at the code below.

static void Main(string[] args)
{
GetConstant(GetInfinity());
}

static int GetConstant(int x)
{

return 0;

}

static int GetInfinity()
{

return GetInfinity() + 1;

}

That looks pretty straightforward code, but if you look closely, we would realize this would end up in a StackOverflowException owing to the infinite recursive GetInfinity Method. If you look furthur closely, do we really need a call to GetInfinity in first place, as GetConstant Method would return a value 0, least bothering the value returned by GetInfinity.

This is where my thought process starts. Cann't the compiler make the decission of whether to make a call to GetInfinity ?

At the end of the day, there are 2 different evaluation orders that could be follows.

a) GetConstant(GetInifinity()) => GetConstant(GetInifinity()+1) => GetConstant(GetInifinity() +1 +1 )....

b) GetConstant(GetInifinity()) =>0

If you notice, the first one never stops while the second one terminates after the first line.

This is something which functional programming languages can take pride in, the Lazy Evaluation.

Wikipedia defines Lazy Evaluation is the technique for delaying a computation until such time as the result of the computation known to be needed.

CLR engages in eager evaluation and hence get it self tangled in the infinite recursive loop in the code above.

I believe this is something Microsoft can bring in the future version of C#. Lazy evaluation can save us quite a bit of time.