Skip to main content
 首页 » 编程设计

c#之你能帮助我理解这个使用 C# 闭包的斐波那契示例吗

2024年02月24日20soundcode

为了学习函数式 C#,我将 Dustin Campbell 的 fibonacci example 移植到了 C#3。我的解决方案有效,但我无法理解 Nth_Fib 的最后一行。公式的补充无关紧要,这不是很奇怪吗? n 立即绑定(bind)到表达式“fn => Nth_Fib(n - 1) + Nth_Fib(n - 2)”,但我无法将构建的返回类型更改为 Func 。这意味着我必须稍后传递一个冗余参数?

注意:测试通过

[TestFixture] 
public class TestFibClosure{ 
    [Test] 
    public void test_fib(){ 
        Assert.AreEqual(8, new FibClosure().Nth_Fib(5)); 
        Assert.AreEqual(1597, new FibClosure().Nth_Fib(16)); 
    } 
} 
 
public class FibClosure{ 
    private Func<int, int>[] formulaCache; 
 
    public int Nth_Fib(int n){ 
        if (n <= 2) return n; 
        if(formulaCache == null) formulaCache = new Func<int, int>[(n + 1)]; 
        Func<int, int> formula = build(n); 
        //doesn't matter, n is already bound !! ?? 
        return formula(334567);//same as formula(n) 
    } 
 
    private Func<int, int> build(int n){ 
        if (formulaCache[n] == null) 
            formulaCache[n] = (fn => Nth_Fib(n - 1) + Nth_Fib(n - 2)); 
        return formulaCache[n]; 
    } 
} 

请您参考如下方法:

您可以将类型更改为 Func<int> - 你只需要在任何地方都这样做:

public class FibClosure{ 
    private Func<int>[] formulaCache; 
 
    public int Nth_Fib(int n){ 
        if (n <= 2) return n; 
        if(formulaCache == null) formulaCache = new Func<int>[(n + 1)]; 
        Func<int> formula = build(n); 
        return formula(); 
    } 
 
    private Func<int> build(int n){ 
        if (formulaCache[n] == null) 
            formulaCache[n] = () => Nth_Fib(n - 1) + Nth_Fib(n - 2); 
        return formulaCache[n]; 
    } 
} 

函数不需要参数,因为它计算的斐波那契值是固定的 - 基本上是 formulaCache[x]将计算 fib(x) .线索是您没有使用 fn。在 build 的 lambda 表达式中无论如何。

我不确定我会说这是一种非常清晰的结构化方式,诚然...