RESTRICTIONS

There are two types of practical restrictions on the use of sequences and ranges in C#. The first type is simply a syntactic one, since complex creation logic results in function calls that aren’t easy to read or understand anymore.

The second type also has to do with the more complex of cases, but it is performance oriented. The Fibonacci examples give an indication of this because they require a data type with two elements to be used. Construction of a sequence using the functional approach requires the previous value to be passed in as the basis of the calculation for the next value. This always involves a certain overhead, which can quickly become prohibitive when the sequence is very long, or when calculations require several values to do their work. Of course there’s the general saying about how premature optimization is usually not a good idea, but because the syntactic issues typically go hand in hand with the ones in the performance area, this forms a natural boundary for the application of functional iterators in C#.

With this in mind, the Fibonacci sequence could be written as an explicit iterator like this:

static IEnumerable<int> FibonacciExplicit(int max) {

  int first = 0;

  int second = 1;

  do

  {

    yield return first;

    int temp = first;

    first = second;

    second += temp;

  } while (max >= first);

}

 

As a better alternative, you could use a different approach by creating an endless sequence implementation, and then limit it externally ...

Get Functional Programming in C#: Classic Programming Techniques for Modern Projects now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.