Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Recursive functions with Lambdas

The below does not compile:

Func<int, int> fac = n => (n <= 1) ? 1 : n * fac(n - 1); 

Local variable 'fac' might not be initialized before accessing

How can you make a recursive function with lambdas?

[Update]

Here are also two links that I found interesting to read:

  1. Eric Lippert's "Why does a recursive lambda cause a definite assignment error?"
  2. Anonymous Recursion in C#
like image 531
Andreas Grech Avatar asked Jul 03 '09 12:07

Andreas Grech


2 Answers

This particular style of function is not supported by C# as a single line declaration. You have to separate out the declaration and definition into 2 lines

Func<int, int> fac = null; fac = n => (n <= 1) ? 1 : n * fac(n - 1); 
like image 57
JaredPar Avatar answered Oct 19 '22 22:10

JaredPar


You'll have to create fac first und assign it later (which is pretty unfunctional because it depends on multiple assignment) or use so called Y-combinators.

Example:

delegate Func<TIn, TOut> FixedPointFunction<TIn, TOut>(Func<TIn, TOut> f);  static Func<T, TRes> Fix<T, TRes>(FixedPointFunction<T, TRes> f) {     return f(x => Fix(f)(x)); }  static void Main(string[] args) {      var fact = Fix<int, int>(f => x => (x <= 1) ? x : x * f(x - 1));      Console.WriteLine(fact(5));             } 

But note that this might be somewhat hard to read/understand.

like image 35
Dario Avatar answered Oct 20 '22 00:10

Dario