CHAINING ITERATORS

Iterators in the form of functions can be used in chains very easily, creating complex processing pipelines out of them. This concept is used a lot in LINQ and also in many of the examples later in this book, and it is one key idea of functional programming. Following are a few examples of the basic idea.

You’ve seen the iterator EndlessListFunction, which returns an endless sequence of integer values. An iterator function that does something to the sequence itself can be used with it. For example, following is an implementation of Take. This function takes a sequence of ints as a parameter together with a count, and only returns the first few elements from the source sequence.

public static IEnumerable<int> Take(int count, IEnumerable<int> source) {

  int used = 0;

  foreach (var item in source)

    if (count > used++)

      yield return item;

    else

      yield break;

}

You can use Take together with EndlessListFunction like this:

var fiveElementList = Take(5, EndlessListFunction( ));

foreach (var item in fiveElementList)

  Console.WriteLine(item);

This is a good example of how iterators can be used as modules. The iterator created by EndlessListFunction can return an unlimited number of elements, but there’s no problem if the algorithm requires only the first few. Only the necessary work is ever executed. You will see improved versions of the Take function later in the book.

The second type of function used in iterator chains is one that employs the ...

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.