Skip to content

Instantly share code, notes, and snippets.

@ErikSchierboom
Last active January 26, 2023 11:28
Show Gist options
  • Save ErikSchierboom/cee479d21120d7c7edddecb424320830 to your computer and use it in GitHub Desktop.
Save ErikSchierboom/cee479d21120d7c7edddecb424320830 to your computer and use it in GitHub Desktop.
Functional february (C# vs F#)

Functional first

let createAddFunction amount =
    let addFunction = fun x -> amount + x
    addFunction

let applyFunction func x =
    func x

let addTwoFunction = createAddFunction 2
let result = applyFunction addTwoFunction 3

printfn "%i" result

Pure functions

C#:

static bool IsMorning()
{
    return DateTime.Now.Hour >= 6 && DateTime.Now.Hour < 12;
}

F#

let isMorning time =
    time.Hour >= 6 && time.Hour < 12;

Immutability

C#:

var point = new Point(4, 6);
point.X = 5;

F#

let point = { X = 4; Y = 6 }
let newPoint = { point with X = 5 };

Recursion

C#:

static int Factorial(int x)
{
    var factorial = 1;

    for (var i = 1; i <= x; i++)
    {
        factorial *= i;
    }

    return factorial;
}

F#

let rec factorial x =
    match x with
    | 1 -> 1
    | _ -> x * factorial (x - 1)

Pattern matching

static string DescribePoints(List<Point> points)
{
    if (points.Count == 0)
        return "No points";
    else if (points.Count == 1)
        return "One point";
    else if (points.Count == 2 && points[1].Y == 0)
        return "Two points, second on x axis";
    else if (points.Count >= 5)
        return "Five or more elements";
    else
        return "Other";
}
let describePoints (points: Point list) =
   match points with
   | [] -> "No points"
   | [_] -> "One point"
   | [_ ; { Y = 0 }] -> "Two points, second on x axis"
   | xs when xs.Length >= 5-> "Five or more elements"
   | _ -> "Other"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment