F# vs C#
Every year I dabble with F# for several weeks. I did this again during the 2016 holiday break. Before I forget what I learned this break I thought it would be good to recap the major benefits of F# over C#.
Better Default Equality
Let's start by defining a Point model in C#. One might make a struct like this:
public struct Point
{
public float X { get; set; }
public float Y { get; set; }
}
In F# you can get the above model with the equality property in much simpler way like this:
type Point = { X:float; Y:float}
In F#, types have built in structural equality and comparison.
Better Compile-Time Checks
F# has a better way of enforcing you cover all cases during compile time. If you make a shape type for squares, rectangles, and circles you could model it like this:
type Shape =
| Square of float
| Rectangle of float * float
| Circle of float
If you were then to go and implement an area function you would implement it like this:
let Area (shape: Shape) =
match shape with
| Square x -> x * x
| Rectangle(h,w) -> h*w
| Circle r -> System.Math.PI * r *r
The compiler forces you to match on Square, Rectangle, and Circle.
Better Handling of NULLs
In C# given a method like this:
public List<string> GetTopPlayers(List<Players> players, int n)
{ ... }
You cannot easily determine what you will get back if you pass in an empty list of players. You might get back a null, an empty list, or an InvalidArgumentException could be thrown.
F# can return what's called "None" and the caller has to handle the "None" case.