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.