Standing on the shoulders of giants. RSS 2.0
# Monday, January 02, 2006

But fun to write:

using System;

class MyClass {
public static void Main() {

int input = 16;
decimal margin = 0.01M;

Func<decimal, decimal> abs = delegate(decimal x) {
return x < 0 ? -x : x;
};

Func<decimal, bool> goodEnough = delegate(decimal guess) {

return abs(guess * guess - input) < margin;
};

Func<decimal, decimal> newGuess = delegate(decimal guess) {
return (guess + input / guess) / 2;
};

Console.WriteLine("guess {0}", Try(1, goodEnough, newGuess) );
Console.ReadLine();
}

static decimal Try(decimal guess, Func<decimal, bool> goodEnough, Func<decimal, decimal> newGuess) {

if (!goodEnough(guess)) {
return Try(newGuess(guess), goodEnough, newGuess);
}

return guess;
}


delegate ReturnType Func<U, ReturnType>(U guess);
}

Inspired by Joel and Chris.

Monday, January 02, 2006 5:37:31 AM (Pacific Standard Time, UTC-08:00)  #    Comments [0] - Trackback
Development
Tracked by:
"Calculate squareroot with C# 3.0" (The glamorous world of software development) [Trackback]
Comments are closed.
Ads
About
© Copyright 2014
Paul van Brenk
Sign In
newtelligence dasBlog 2.3.12105.0
All Content © 2014, Paul van Brenk
DasBlog theme 'Business' created by Christoph De Baene (delarou)