Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Help with LINQ Expression

Tags:

c#

linq

fibonacci

How to write a LINQ Expression (method call syntax preferred) that gives a list of fibonacci numbers lying within a certain range, say 1 to 1000 ?

like image 836
missingfaktor Avatar asked Nov 30 '22 06:11

missingfaktor


1 Answers

OK; for a more "FP" answer:

using System;
using System.Collections.Generic;
using System.Linq;
static class Program
{
    static void Main()
    {
        Func<long, long, long, IEnumerable<long>> fib = null;
        fib = (n, m, cap) => n + m > cap ? Enumerable.Empty<long>()
            : Enumerable.Repeat(n + m, 1).Concat(fib(m, n + m, cap));

        var list = fib(0, 1, 1000).ToList();
    }
}

Note that in theory this can be written as a single lambda, but that is very hard.

like image 107
Marc Gravell Avatar answered Dec 08 '22 15:12

Marc Gravell