Fibonacci With Generator - CSharp Collection

CSharp examples for Collection:Iterator

Description

Fibonacci With Generator

Demo Code

using System;//from   ww w .  ja  va 2s  .c  o m
using System.Collections.Generic;
using System.Linq;
class FibonacciWithGenerator
{
   static void Main()
   {
      var fibonacci = GenerateSequence(
      (current: 0, next: 1),
      pair => (pair.next, pair.current + pair.next),
      pair => pair.current);
      foreach (var value in fibonacci.Take(10))
      {
         Console.WriteLine(value);
      }
   }
   static IEnumerable<TResult> GenerateSequence<TState, TResult>(
   TState seed,
   Func<TState, TState> generator,
   Func<TState, TResult> resultSelector)
   {
      var state = seed;
      while (true)
      {
         yield return resultSelector(state);
         state = generator(state);
      }
   }
}

Result


Related Tutorials