Saturday, February 09, 2013

Useful Things to Know, #429: Recursive Anonymous Functions

If you’ve ever tried to code an anonymous function that calls itself, you may have concluded that it can’t be done.  After all, trying the following …

 Func<int, int> collatz = (n) =>
{
if (n == 1)
return 0;
if (n % 2 == 0)
return collatz(n/2) + 1;
else
return collatz(3 * n + 1) + 1;
};

… leads to the message:  “Error:  Use of unassigned local variable ‘collatz’”.

And this makes sense:  the delegate “collatz” doesn’t have a value until after the execution of the assignment statement in which you’re referencing it!

But the error message contains the key to making it work.  The message says that “collatz” is unassigned.  So in order to use it in an expression, assign it an initial value before assigning it your recursive anonymous function.

Func<int, int> collatz = null;
collatz = (n) =>
{
if (n == 1)
return 0;
if (n % 2 == 0)
return collatz(n/2) + 1;
else
return collatz(3 * n + 1) + 1;
};

(If you’re wondering what problem that function could possibly solve, check here.)

Labels:

1 Comments:

Blogger Padminiprwatech said...

Thanks for sharing your innovative ideas to our vision. I have read your blog and I gathered some new information through your blog. Your blog is really very informative and unique. Keep posting like this. Awaiting for your further update. If you are looking for any Python programming related information, please visit our website python training institute in Bangalore

12/12/2019 2:30 AM  

Post a Comment

<< Home