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;
      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
      (g) => ((square / g + g) / 2),
      (c, n) => Math.Abs(c - n) > epsilon)
      select guess;

   return sequence.Last();
comments powered by Disqus
Most   Popular
Upcoming Events

.NET Insight

Sign up for our newsletter.

Terms and Privacy Policy consent

I agree to this site's Privacy Policy.