missingfaktor missingfaktor - 2 months ago 50
C# Question

Help with LINQ Expression

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 ?


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.