I added this code as a comment to a thread that was almost all the way off the front page by the time I got to it. It was a response to some 'functional folks' criticizing the verbosity of c#. While you can certainly do c# the java way, you can also do it in a
near functional way.
I decided to post the code as a full submission because I think c# often gets dismissed as Java copy-cat, which hasn't been true in a decade.
The code (non-destructive, no side effects) calculates square roots :
public static void Main()
{
const int n = 21;
Observable.Generate<double,double>(1, x=>true, x=> 0.5 * (x + (n/x)), x=>x )
.Scan(new {prv = 0d, cur = 0d}, (prev, curr) => new {prv = prev.cur, cur = curr})
.FirstAsync(_ => Math.Abs(_.cur - _.prv) < 1E-10)
.Select(_ => _.cur)
.Subscribe(Console.WriteLine);
// this is just to compare values, so is not part of the solution
Console.WriteLine(Math.Sqrt(n));
Console.ReadLine();
}
Read the more OO c# implementation that inspired me here:
https://news.ycombinator.com/item?id=7044497
Read the Haskell code that inspired both here:
https://news.ycombinator.com/item?id=7043943
Or Python, via RxPy: https://github.com/Reactive-Extensions/RxPy
Or JavaScript, via RxJs: https://github.com/Reactive-Extensions/RxJS
Or Ruby, via Rx.rb: https://github.com/Reactive-Extensions/Rx.rb
Or Objective-C, via Rx.ObjC: https://github.com/Reactive-Extensions/Rx.ObjC
Your code is a good demonstration of how Rx works though, and it's nice to know it's becoming more popular.