Saturday, June 23, 2012

Lazy List in C#

I was playing around with some F# code and thinking about lazy lists in Haskell and how I could get them in F#. Well, since I know how to make an enumerable function in C# I decided to have a go making one in that instead.

void Main()
{
foreach (var i in LazyRange(1, (n) => ++n).Take(10))
{
System.Console.WriteLine(i);
}

System.Console.WriteLine();

var fizz = LazyRange(1, (n) => ++n)
.TakeWhile(n => n < 1000)
.Where(n => n % 3 == 0 || n % 5 == 0)
.Sum();

System.Console.WriteLine(fizz);
}

IEnumerable<T> LazyRange<T>(T start, Func<T, T> successor)
{
T value = start;
while (true)
{
yield return value;
value = successor(value);
}
}

To use it supply a starting value and a function to provide each successive value. Use Take or TakeWhile to limit the collection otherwise you will end up with an infinite list.

No comments:

Post a Comment