Click here to Skip to main content
15,905,612 members
Please Sign up or sign in to vote.
2.00/5 (2 votes)
See more:
how to implement lambas recursively.
Posted
Comments
bowlturner 6-Jan-14 12:26pm    
what do you mean? Do you mean to check lists of lists? Give us an example of what you are looking for.
RajaSekhar Korimilli 6-Jan-14 12:41pm    
We are familiar with recursive functions. similarly, as lambdas are the function objects without any name, how do we implement them using recursion. explain with an example so that i can get to know about the use of recursive lambdas

Solution 1 is pretty good but it leaves a vulnerability for error.
It depends on the binding to the name factorialValue for the recursive call.
If were compromised it falls apart.
Very contrived example:
C#
Func<int, int> Factorial = null;
Factorial = x => (x <= 0) ? 1 : x * Factorial(x - 1);
Func<int, int> incorrectFactorial = Factorial;
Factorial = x => x;

int ans = incorrectFactorial(5);

The value of ans here is 20 because of the reassignment of the identifier Factorial.
The name binding the recursive method needs to be protected:
C#
Func<int, int> Factorial = null;
Factorial = x => {
  Func<int, int> internalFactorial = null;
  internalFactorial = xi => (xi <= 0) ? 1 : xi * internalFactorial(xi - 1);
  return internalFactorial(x);
};

Func<int, int> otherFactorial = Factorial;
Factorial = x => x;

int ans = otherFactorial(5);

Here the value of ans is the correct 120 because the recursion identifier was internal to the scope of the lambda.
Another way to accomplish this would be to have a method that returns a Func<int, int>:
C#
static Func<int, int> GetFactorialFunction()
{
  Func<int, int> Factorial = null;
  Factorial = x => (x <= 0) ? 1 : x * Factorial(x - 1);
  return Factorial;
}

and invoke the returned function:
C#
int ans = GetFactorialFunction()(5);

Of course, at this point using a lambda is probably superfluous since the function could be implemented directly as a named, recursive function.
 
Share this answer
 
Comments
Karthik_Mahalingam 6-Jan-14 20:13pm    
5,good
BillWoodruff 6-Jan-14 22:47pm    
+5 far out, man !
Its possible to implement lambda recursively.
Try this as an example
XML
Func<int, int> factorialValue = null;
factorialValue = x => (x == 0) ? 1 : x * factorialValue(x - 1);
 
Share this answer
 
Comments
Karthik_Mahalingam 6-Jan-14 20:12pm    
5,good
Abhinav S 6-Jan-14 22:09pm    
Thank you.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900