Can someone show me how to implement a recursive lambda expression to traverse a tree structure in C#.
A simple alternative is to “go back in time” to the antics of C and C++: declaration before definition. Try the following:
Funcfact = null; fact = x => (x == 0) ? 1 : x * fact(x - 1); Works like a charm.
Yes, that does work, with one little caveat. C# has mutable references. So make sure you don't accidentally do something like this:
Func fact = null;
fact = x => (x == 0) ? 1 : x * fact(x - 1);
// Make a new reference to the factorial function
Func myFact = fact;
// Use the new reference to calculate the factorial of 4
myFact(4); // returns 24
// Modify the old reference
fact = x => x;
// Again, use the new reference to calculate
myFact(4); // returns 12
Of course, this example is a bit contrived, but this could happen when using mutable references. If you use the combinators from aku's links, this won't be possible.