Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a Func<> call itself recursively?

Tags:

c#

.net

recursion

I was playing around with a code golf question yesterday for building a christmas tree which came around last year and I threw together a quick recursive algorithm to do the job:

static string f(int n, int r)
{
    return "\n".PadLeft(2 * r, '*').PadLeft(n + r)
        + (r < n ? f(n, ++r) : "*".PadLeft(n));
}

I got to wondering if I could do the same thing with a Func:

Func<int,int,string> f = (n, r) => {
    return "\n".PadLeft(2 * r, '*').PadLeft(n + r) 
        + (r < n ? f(n, ++r) : "*".PadLeft(n));
};

This would do the job except that the recursive part doesn't recognize that the call to f is actually a call to itself. This would lead me to conclude that a Func can't call itself recursively - but I wonder if I'm drawing false conclusions or if it can be done but requires a different approach.

Any ideas?

like image 562
BenAlabaster Avatar asked Nov 20 '09 15:11

BenAlabaster


People also ask

Can the main function call itself recursively?

The main() function can call itself in C++. This is an example of recursion as that means a function calling itself.

Can a function be called in itself?

Recursion is an extremely simple concept: a function simply calls itself. Recursion refers to a function that calls itself either directly or indirectly.

Which function Cannot use recursion?

Explanation: There is nothing recursion can compute that looping can't, but looping takes a lot more plumbing.


2 Answers

Func<int, int, string> f = null;
f = (x, y) => f(x, y);

Obviously this will cause a StackOverflowException, but you get the idea.

like image 155
Yuriy Faktorovich Avatar answered Sep 28 '22 07:09

Yuriy Faktorovich


See this for a very geeky coverage of recursive lambdas, fixed points, Y-combinators, etc. Very interesting read.

like image 22
Anton Gogolev Avatar answered Sep 28 '22 07:09

Anton Gogolev