Treat Code as Data: C#: Implement a Functional Version of Hero Roots: Listing 4
This implementation defines four functions (two inline) that implement the same algorithm. The algorithm is now a declarative version that defines what happens, rather than how you create it.
public static IEnumerable<T> GenerateSequence<T>(
T seed, Func<T, T> NextValue,
Func<T, T, bool> More)
{
T nextVal = seed;
Do
{
seed = nextVal;
yield return nextVal;
nextVal = NextValue(seed);
}
while (More(seed, nextVal));
}
public static double HeroRootFunc(
double square, double epsilon)
{
var sequence = from guess in
MyExtensions.GenerateSequence(1.0,
(g) => ((square / g + g) / 2),
(c, n) => Math.Abs(c - n) > epsilon)
select guess;
return sequence.Last();
}