Exercises in this lecture               Go to the notes, in which this exercise belongs -- Keyboard shortcut: 'u'   Alphabetic index   Course home      

Exercise 12.8
Infinite Collections of Integers


In several respects, this exercise previews ideas from LINQ.

Program a class IntegersFrom which represent an inifinite sequence of integers (of type long) from a given starting point. The class must implement the interface IEnumerable<long>.

First, program a version without use of yield return, and next program a version which uses yield return. Compare the two versions. (It is surprisingly tricky to program the version which uses native iterators (enumerators) in C#, without using yield return. You may chose to study my implementation (in the solution) instead of spending time on programming the class yourself.)

As an alternative to the class IntegersFrom, make an extension method AdInifinitum (which means 'to inifinity') in the type long , which enumerates an infinite sequence of integers from a given starting point:

    public static IEnumerable AdInfinitum(this long from){...}

Make an additional extension method in the interface IEnumerable<long> which filters an infinite sequence of integers with use of a given predicate

   
  public static IEnumerable<long> Filter(this IEnumerable<long> source, 
                                         Func<long, bool> pred){...}

Use Filter to obtain all even integers, and all primes.

Finally, program an extension method in IEnumerable<long> that adds two infinite sequences of integers together (pair-by-pair):

    
  public static IEnumerable<long> Add(this IEnumerable<long> source,
                                      IEnumerable<long> other){...}

Add all natural numbers, lL.AdInfinitum(), to itself, and get all even numbers again.


Solution