BenAlabaster
BenAlabaster

Reputation: 39874

Can a Func<> call itself recursively?

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?

Upvotes: 7

Views: 1298

Answers (2)

Anton Gogolev
Anton Gogolev

Reputation: 115867

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

Upvotes: 5

Yuriy Faktorovich
Yuriy Faktorovich

Reputation: 68737

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

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

Upvotes: 17

Related Questions