用于在C#中遍历树的递归lambda表达式

Joe*_*ham 63 c# recursion lambda

有人可以告诉我如何实现递归的lambda表达式来遍历C#中的树结构.

aku*_*aku 72

好的,我终于找到了一些空闲时间.
开始了:

class TreeNode
{
    public string Value { get; set;}
    public List<TreeNode> Nodes { get; set;}


    public TreeNode()
    {
        Nodes = new List<TreeNode>();
    }
}

Action<TreeNode> traverse = null;

traverse = (n) => { Console.WriteLine(n.Value); n.Nodes.ForEach(traverse);};

var root = new TreeNode { Value = "Root" };
root.Nodes.Add(new TreeNode { Value = "ChildA"} );
root.Nodes[0].Nodes.Add(new TreeNode { Value = "ChildA1" });
root.Nodes[0].Nodes.Add(new TreeNode { Value = "ChildA2" });
root.Nodes.Add(new TreeNode { Value = "ChildB"} );
root.Nodes[1].Nodes.Add(new TreeNode { Value = "ChildB1" });
root.Nodes[1].Nodes.Add(new TreeNode { Value = "ChildB2" });

traverse(root);
Run Code Online (Sandbox Code Playgroud)

  • @VVS它存在于List <> http://msdn.microsoft.com/en-us/library/bwabdf9z.aspx (4认同)

Kon*_*lph 27

一个适当的解决方案,实际上是许多函数式编程语言中的惯用解决方案,将是使用定点组合器.简而言之:定点组合器回答了"我如何定义匿名函数是递归的?"的问题.但解决方案是如此不同寻常,以至于整篇文章都是用来解释它们的.

一个简单,实用的替代方案是在定义之前"回溯到C:声明的滑稽动作".请尝试以下方法:

Func<int, int> fact = null;
fact = x => (x == 0) ? 1 : x * fact(x - 1);
Run Code Online (Sandbox Code Playgroud)

奇迹般有效.

  • 因为它是递归的 (9认同)
  • 出于好奇,这个阶乘函数如何帮助回答特定问题? (2认同)

Tom*_*rst 15

一个简单的替代方案是"回溯到C和C++的滑稽动作:定义之前的声明".请尝试以下方法:

Func<int, int> fact = null;
fact = x => (x == 0) ? 1 : x * fact(x - 1);
Run Code Online (Sandbox Code Playgroud)

奇迹般有效.

是的,这确实有效,但有一点需要注意.C#有可变引用.因此,请确保您不会意外地执行以下操作:

Func<int, int> fact = null;
fact = x => (x == 0) ? 1 : x * fact(x - 1);

// Make a new reference to the factorial function
Func<int, int> 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
Run Code Online (Sandbox Code Playgroud)

当然,这个例子有点人为,但是在使用可变引用时可能会发生这种情况.如果你使用aku链接中的组合器,这是不可能的.