Part I. A Simple Expansion
If we define a Expand() extension method for a Func<T,T> delegate type we can use it to generate lists. This method will calculate indefinitely in the while loop so we'll have to be careful to constrain the output.
/// <summary>
/// <para>Expands indefinately starting with the seed.</para>
/// <para>Warning: this is an infinite loop and a slice of the output must be selected</para>
/// </summary>
public static IEnumerable<T> Expand<T>(this Func<T, T> generator, T pSeedA)
{
while (true)
{
yield return pSeedA;
pSeedA = generator(pSeedA);
}
}
For an example, if we define a delegate to calculate a single decay calculation of .99 (or 1% decay), then we can call Expand() method passing an initial seed value and our method will calculate a never-ending list of exponentially decaying results. We'll take the 251st item to see what our value has decayed to.
Console.WriteLine("\n\nAfter 250 intervals of decay at a rate of 0.99, the value 100000.00 is now " +
new Func<Double, Double>(x => x * 0.99)
.Expand(100000.00) // seed value
.Skip(250) // skip the first 250
.First() // get the next _disibledevent=MsoBodyText>Until next time,
Happy coding
最新评论