I just started playing with lambdas and Linq expression for self learning. I took the simple factorial problem for this. with the little complex scenario where find the fact
Just to continue on Jon's answer, here's how you can memoize the factorial function so that you don't recompute everything at each step :
public Func Memoize(Func func)
{
Dictionary _resultsCache = new Dictionary();
return (arg) =>
{
TResult result;
if (!_resultsCache.TryGetValue(arg, out result))
{
result = func(arg);
_resultsCache.Add(arg, result);
}
return result;
};
}
...
Func factorial = null; // Just so we can refer to it
factorial = x => x <= 1 ? 1 : x * factorial(x-1);
var factorialMemoized = Memoize(factorial);
var res = Enumerable.Range(1, 10).Select(x => factorialMemoized(x));
foreach (var outt in res)
Console.WriteLine(outt.ToString());
EDIT: actually the code above is not correct, because factorial calls factorial, not factorialMemoized. Here's a better version :
Func factorial = null; // Just so we can refer to it
Func factorialMemoized = null;
factorial = x => x <= 1 ? 1 : x * factorialMemoized(x-1);
factorialMemoized = Memoize(factorial);
var res = Enumerable.Range(1, 10).Select(x => factorialMemoized(x));
foreach (var outt in res)
Console.WriteLine(outt.ToString());
With that code, factorial is called 10 times, against 55 times for the previous version