tags:

views:

158

answers:

2

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?

+10  A: 
Func<int, int, string> f = null;
f = (x, y) => f(x, y);

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

Yuriy Faktorovich
Good remark about the StackOverflowException.
Darin Dimitrov
LOL - I get the gist of it. It's too bad you can't do it all in a single line though. Thanks.
BenAlabaster
Spot on. Ben's code is illegal for the same reasons as 'int i = i + 1;'Also note that f's code block could reassign the value of f, which would be obtuse but perfectly legal.
Rob Fonseca-Ensor
@Nick: Why not?
John Gietzen
Yeah - don't write this exact code, but it answers the question in principle
Rob Fonseca-Ensor
No pun intended.
Yuriy Faktorovich
@Rob: In the case of your example `int i = i + 1` that makes sense what is the value of 'not initialized' + 1? It seemed to me to be logical that 'f' is assigned the code block when calling `f = ...` but when calling f(n, r) it would actually be calling itself. Given that f would need to have been initialized in order to for the code block to be executing to call itself, it makes logical sense that this would work (at least on a human level).
BenAlabaster
I describe the reason why this is an error here: http://blogs.msdn.com/ericlippert/archive/2006/08/18/why-does-a-recursive-lambda-cause-a-definite-assignment-error.aspx
Eric Lippert
@Eric Lippert: Thank you Eric, I appreciate your attention. Now go and make it work so my code can be even more elegant than it already is :P
BenAlabaster
+4  A: 

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

Anton Gogolev
Very interesting read - but it hurts my head :P
BenAlabaster