More functional C#
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=7044497Read the Haskell code that inspired both here: https://news.ycombinator.com/item?id=7043943
97 comments
[ 4.1 ms ] story [ 92.1 ms ] threadPS: once Roslyn get's finally released, Java will never catch up again.
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.
Sure, it does, but why would you use it like that?
Have a look at http://www.indeed.com/jobanalytics/jobtrends?q=c%23%2C+f%23&...
And someone has to maintain your near functional or functional code
You don't have to hire developers from outside to bring new technologies into a company. In fact, given the scarcity (i.e., demand > supply) of good developers these days, it's almost certainly going to be easier and faster to have your existing development staff learn those new technologies vs. trying to hire new developers with experience in those technologies.
I think I actually spent more time learning Entity Framework than I did learning F#, and EF still catches me with weird edge cases. Meanwhile F#'s crazy smart compiler is catching all mine ;)
Also, with default immutability, type providers, and less boilerplate I feel a lot more confident with the quality of the code I write, and I am able to write it faster.
Since it's possible to do full C#-style OO in F#, I personally don't see a reason to use C# at all. F# is more supporting of a multi paradigm codebase, it's safer, and requires less code to do the same things as C#. Combine that with what I would consider to be an extremely short learning curve, I am happy finding C# programmers and letting them learn F# the first week of the job.
I like F# though. But I think it takes some getting used to, and I'm not quite there yet. :)
Each paradigm gets used depending on the type of problem being solved.
I must conclude, by the usual Stroustrup quote, that no one uses C#. (yes this is tongue in cheek)
Mono is significantly more important for the future of C# than Windows Phone.
What makes you think Mono plays (or is about to play) such a pivotal role?
The whole notion of .NET only being suitable for enterprise development is bullshit.
At least right now, MS is still seen (although less lately) like the Big Bad, so giving them money to use what you can get for free or near-free elsewhere seems uncool and like bad business sense.
I suspect too from my own extremely limited sample size that .NET developers make more money on average than the average of the other languages, so that is also a liability when looking for talent when you have limited cash.
I think its free version is still better than most paid VS editions. The $500 edition is the best IDE I've seen. And it supports basically every language but the three .NET languages.
Think of the costs of paying your developers. Those things are a pittance compared to the cost of hiring and retaining good developers.
http://www.visualstudio.com/en-us/products/how-to-buy-vs
Then most drop another couple hundred to make it actually have some of the cool Intellij IDEA features by adding in Resharper. I'm not trying to hate, I use VS at work, just I can see why it's not a popular startup ecosystem.
What I don't get is: if people aren't even buying the top line IDE to use all its features, and are just buying the crappy subset IDEs, why use .NET at all? Where's the value proposition over Java/Scala? It runs on fewer architectures, the language is only mildly better than Java and certainly not better than Scala, and the long promoted IDE has less features and is exorbitantly overpriced. I just don't get it. Is it just inertia at this point? The question in my mind isn't: "why are so few startups using it?" It's "why is anyone still picking that as their business's main stack?"
I know my team is currently locked in to agreements with other companies who require it (naturally). So when a new customer wants our stuff, they have to handle it. Is that the main reason? Everyone using it is in a circle of dependence?
Oh I forgot to mention, the functionality of Fakes used to be free, but in the new iteration it no longer is, so they can squeeze a few more 13k editions.
I've never really bought the argument that building for .NET is too expensive. Yes, it's a lot more expensive than free, but for a company it's peanuts when it guarantees the company a stable platform and a growing dev market. The only people that will be priced out are bootstrappers. I've built more small-business sites on Umbraco than I can count.
Tuple<string, IEnumerable<string>, IEnumerable<KeyValuePair<string, bool>>
I've come to a point where I can comfortably write functional code in the language (though I should stress that I don't write "pure" functional code; I don't fall into the camp that abhors side effects in all scenarios). Day to day, it really is a fine language to work in, notwithstanding a few warts. In all honesty though, I'd rather be working in Python or a LISP most of the time
But in general it's a very solid choice. You can even get around a lot of the inefficiency of GC by careful usage of structs.
I never got the verbosity argument. Verbosity comes down to the person using the language. With C#, you can be as verbose as you want to. Do you have any examples?
What kind of inefficiency are you speaking of? the CLR's GC is one of, if not the, most efficient around.
[0] http://msdn.microsoft.com/en-gb/roslyn
I do consider C# more verbose than the languages I love to look at. Think 'SelectMany', 'FirstOrDefault' and similar constructs - even if you write functional C# as much as possible, it still .. is verbose. If compared to F#, Clojure for example.
I don't think that's an issue, mostly, but that I do agree with the notion that C# is 'verbose'.
Sure, write a self-executing function in C#.
While there's plenty of limitations and frustrations you can run into with C#, I've generally felt they were largely due to intentional tradeoffs I can understand, and fail to know a better alternative to. This makes me significantly less ranty about it, in contrast to my other daily bread and butter of C++. Even if I felt both were as limiting as each other, I'd be ranting about the latter significantly more -- simply out of a sense that "it shouldn't have to be this way".
Absent any other evidence, one should assume the amount of complaining a language would get is about proportional to how widely it's used. So the lack of complaining (asserted by the parent) about C# might be as much a reflection on how widely it's used, than on the language itself.
[0]: http://www.tiobe.com/index.php/content/paperinfo/tpci/index....
I disagree that Dewie's individual experience constitutes a "base-rate". If you're referring to something else as a "base-rate", you'll have to spell it our more clearly for me, as I'm having difficulty seeing how to apply it validly here.
> Absent any other evidence, one should assume the amount of complaining a language would get is about proportional to how widely it's used.
That's reasonable, and my own experiences and anecdotes don't turn out to be capital D Data. However, neither are Dewie's experiences and anecdotes. And what I would argue isn't reasonable is assuming the amount of complaining that one individual developer hears about a language we get is about proportional to how widely it's used. The data set is far too small to extrapolate that far.
My own experience is that the amount of complaining about a language I hear about varies wildly by what my peers in my communities happen to be using at the time. I went years without hearing any complaints about PHP... and then someone gets employed writing it and it spikes up to the language I hear the most complaints about. I'd be very absurd to assume that PHP went from not used very widely at all to the most used language in that same timeframe!
While I cast a wide net, my time is finite and I pay more attention to some communities than others, quite understandably biasing what I hear significantly.
> So the lack of complaining (asserted by the parent) about C# might be as much a reflection on how widely it's used, than on the language itself.
Granted, but "might be" is a far cry from "is" or "should be assumed to be". Indeed, I wouldn't suggest that "C# might generally be less rant-inducing" to be worthy of assuming either. Dewie "might be" not hanging around .NET devs, but even that's a terribly poor assumption -- I know plenty of devs who don't complain about languages I consider absolutely terrible.
I've been using C# for about 3 years now. A year or two into using it I thought I was developing fanboy syndrome so I started a list of all of the dumb quirks and pitfalls the language has. Last time I checked, there were only 3 or 4 items on the list compared my python/c++/java lists which have 1-2 orders of magnitude more quirks.
C# really is a solid language, it's just a terrible shame it had to have the Microsoft label attached to it.
http://hestia.typepad.com/flatlander/2012/01/action-func-voi...
http://trelford.com/blog/post/LighterCSharp.aspx
http://stackoverflow.com/questions/411906/c-sharp-net-design...
http://joeduffyblog.com/2010/06/27/on-partiallyconstructed-o...
http://blogs.msdn.com/b/dsyme/archive/2013/03/25/quote-of-th...
Anyway, no one's saying C# is flawless. Personally, I would love the ability to declare immutable graph references.
I fail to see how it is an "obvious critical flaw" :)
No, it's simply not true that you need "an identical implementation except for omitting the return keyword"...Eg. this would do the trick without repeating the implementation: http://pastie.org/8628864
Just two one-line overloads as entry points.
The problem is that void can't be used as a regular type identifier.
In a lot of langages (like Python, Haskell, F#, ...) there is a regular type for void. This type is often implemented as such :
Then you can define Action<...> just as Func<Void, ...>.As the compiler is smart enough to see there is only one kind of Void value, it can be entierly removed from the generated code and thus doesn't make your code slower.
I'd rather have code written in simple, well factored functions and classes and easy to reason about, than having to deal with such a mess of functional code.
Don't get me wrong, functional code can be very elegant and clear, but the example provided here is a huge turn off to me.