by lucianp · 12y ago · 0 comments
I'm currently working on a big C# codebase and it would be interesting to see if F# would make some of it cleaner.
http://fsharpforfunandprofit.com/series/why-use-fsharp.html
It compares and contrasts C# and equivalent F# code for relatively simple, but common-in-the-real-world examples, while introducing some functional constructs. I'd also recommending reading the "Thinking Functionally" series.
After that I'd recommend skimming some of the topics on the F# wikibook:
http://en.wikibooks.org/wiki/F_Sharp_Programming
And then I'd begin with rewriting some components in your existing project while continuing reading through that book and other online resources.
Me and a coworker also rewrote ~600 line C# module into a working module in F#, along with some interop POC here: https://github.com/cartermp/CSharpToFSharp
It's the product of a little over 20 hours of development across two people new to the language (and thus has some warts...), so take it as a grain of sand. Uses MS Unit Testing framework for F# (available via NuGet).
F#'s benefit will come as a bunch of tiny improvements, "programming in the small" as they call it. For instance:
let xs = [ while r.Read() do yield r.GetInt 0 ]
In C#, it's: var xs = new List<int>();
while (r.Read()) { xs.Add(r.GetInt(0)); }
Or: let f x =
let x = try int s with _ -> -1
x * 3
In C#, it's uglier. First because try... isn't an expression. Second, because you cannot shadow variables by rebinding them, so you always have to keep "old" vars around and in scope, and cannot reuse handy variable names: int f(string x) {
int x1;
try { x1 = int.Parse(s); }
catch { x1 = -1; }
return x1 * 3;
}
Or: let x =
use db = new DB()
db.GetX()
In C#, you've got to declare x outside a block: SomeType x;
using(var db = new DB()) {
x = db.GetX()
}
Which is more annoying than it might seem. How much nicer is it to be able to create a new scope at any point in a function, and return a value out of it cleanly?These are by no means a complete or even important showcase of C#'s lacking. Just a few quick thoughts off the top of my head. In general, every time I'm writing C# code, I keep realising how things would be much more concise if I was in F#.
1) Simply write a quick extension method (not ideal but not a reason to switch languages):
var xs = r.YourExtensionMethod<int>(rr => rr.GetInt(0)).ToList();
2) Simply use the appropriate built-in method: int f(string x)
{
int number; /*Will be not necessary in C#6.*/
return Int32.TryParse(value, out number) ? numeber * 3 : -1;
}
3) It's a matter of taste. Not a bad feature, but not a killer one either.http://msdn.microsoft.com/en-us/library/vstudio/hh314518%28v...
- Accessing the DB is easier in C# (just select a nice micro-ORM), type providers do not always cut it.
- When using any kind of library that relies on anonymous types (e.g. Dapper for database access).
- Tooling is still not complete, not being able to create directories in F# project (!) from IDE level (and even if you edit .fsproj, it can be a bit buggy) is really annoying in both web and desktop apps.
- If you want to use some of object-oriented features e.g. co/contravariance in interfaces, protected access modifier.
- (admittedly, that does not happen often) no unsafe context/keyword
That being said, I agree that F# has a very sane set of defaults and I really like using F# for library work.
The rest of the real arguments are essentially "library support". Which is a good argument, but not really about the language itself. There's no reason that WPF, DB access, etc. can't be just as fine in F#.
(C#'s limitations, like no tuples, led high-profile projects like ASP.NET MVC to do dumb hacks like "pass in an object and we'll assume each field is a parameter". If C# had been more capable in the first place, they wouldn't have resorted to such hacks.)
You shouldn't be writing WPF apps at all.
In general, I find writing in C#, I'm going to need 50-200% more code for "business logic" type code that doesn't particularly benefit from F#. That is, using F# as a better C#. And this is after C# hacked in async - before that, there's no comparison if you need async style code.
If C# added pattern matching, tuples, active patterns, type inference, everything-as-an-expression, nesting, more comprehensions, etc. etc., then yes, C# would be competitive. And with all the resources C# gets, the IDE would be far better than F#, sure.
C# is for legacy and large corporate red-tape-encumbered enterprise projects only, as far as I'm concerned.
But then what of C#, which lacks object expressions? Which forces you to declare a type, often an interface, just to implement a member or two?
In the enterprise C# is the way to go. You won't find many Fortune 500 companies, with offshoring projects, going F# instead of C#.
For many 9 - 5 developers, C# is already too complex, many of each are ex-VB developers.
F# lacks the Visual Studio tooling support for the typical enterprise projects workflow and frameworks.
Also, the .NET libraries we end up using were, to my knowledge, written in C#. Sometimes interacting with them feels awkward if done functionally.
I noticed that was something certain folks tended to do, they'd insist on creating an expression as a series of folds and maps, even if it had a very simple expression otherwise (as a list comprehension or simple for..in loop). Cast those cares aside, and write what is most useful for your use case.
Sometimes though, you do want break/goto/continue, although in most cases I think such code is better off in C or Rust.
It's impossible (and foolish) to avoid C# if you develop for Windows, but I haven't written a single line of C# since 2004.