Wednesday, March 9, 2011

Computing factorials by using iterator blocks (yield -> return -> fun)

Likewise iterator blocks are a mystery to many developers. Unless you've already been thinking in sequences, you may well have never written an iterator block.
- by Jon Skeet

I just have implemented my first iterator block for factorial computing! Here follows code:
using System;
using System.Collections;

namespace CSharpIterators
{
 class MainClass
 {
  public static IEnumerable Factorial (int number)
  {
   if (number < 0) {
    throw new ArgumentOutOfRangeException ("number");
   }
   
   int result = 1;

   yield return 1;

   for (int i = 1; i < number; i++) {
    result = result * i;

    yield return result;
   }
  }

  public static void Main (string[] args)
  {
   int count = 0;
   foreach (int i in Factorial (8)) {
    Console.WriteLine ("{0} = {1}; ", count++, i);
   }

   Console.WriteLine ("Done...");
   Console.ReadLine ();
  }
 }
}
If you haven't heard about those fancy iterators you better start learning now! Go here read the simplest explanation ever I read on this subject.

Truly yours
Darius :)