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?
The main() function can call itself in C++. This is an example of recursion as that means a function calling itself.
Recursion is an extremely simple concept: a function simply calls itself. Recursion refers to a function that calls itself either directly or indirectly.
Explanation: There is nothing recursion can compute that looping can't, but looping takes a lot more plumbing.
Func<int, int, string> f = null;
f = (x, y) => f(x, y);
Obviously this will cause a StackOverflowException, but you get the idea.
See this for a very geeky coverage of recursive lambdas, fixed points, Y-combinators, etc. Very interesting read.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With