HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Recursive Fibonacci with Generic delegates

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
genericfibonacciwithrecursivedelegates

Problem

Here is a fast recursive Fibonacci-like for loop. How can it be more readable, and is it possible remove TArgs?

public static class Fibonacci
{
    public static BigInteger Calculate(BigInteger number)
    {
        var fibo = AnonRecursiveFiboFunc(
            func => (step, fibo1, fibo2) => step == number
            ? fibo2
            : func(++step, fibo1 + fibo2, fibo1));
        return fibo(0, 1, 0);
    }

    delegate Func
        Recursive(
        Recursive r);

    private static Func 
        AnonRecursiveFiboFunc(Func,
                                         Func> function)
    {
        Recursive recursive = 
            rec => (step, fibo1, fibo2) => 
                function(rec(rec))(step, fibo1, fibo2);
        return recursive(recursive);
    }
}

Solution

-
I like to say T1 T2 instead of TArg1, it just makes it more clear to me what is going on. Your code would look more like this.

delegate Func Recursive( Recursive r);

private static Func AnonRecursiveFiboFunc(Func, Func> function)
{
    Recursive recursive = rec => (step, fibo1, fibo2) => function(rec(rec))(step, fibo1, fibo2);
    return recursive(recursive);
}


Other than that... this code seems pretty solid, except for the crazy lack of immediate readability :D and like mentioned in the comments the fact that you are using delegates at all here.

Code Snippets

delegate Func<T1, T2, T3, T4> Recursive<T1, T2, T3, T4>( Recursive<T1, T2, T3, T4> r);

private static Func<T, T, T, T> AnonRecursiveFiboFunc<T>(Func<Func<T, T, T, T>, Func<T, T, T, T>> function)
{
    Recursive<T, T, T, T> recursive = rec => (step, fibo1, fibo2) => function(rec(rec))(step, fibo1, fibo2);
    return recursive(recursive);
}

Context

StackExchange Code Review Q#44602, answer score: 5

Revisions (0)

No revisions yet.