Recursive lambda expression to traverse a tree in C#

后端 未结 4 1232
萌比男神i
萌比男神i 2020-12-04 10:35

Can someone show me how to implement a recursive lambda expression to traverse a tree structure in C#.

4条回答
  •  甜味超标
    2020-12-04 10:49

    A simple alternative is to “go back in time” to the antics of C and C++: declaration before definition. Try the following:

    Func fact = 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.

提交回复
热议问题