F#
01 / 02

F# Fundamentals: Immutability, Types & Pattern Matching

F#: Immutability, Types & Pattern Matching

F# is a functional-first language on the .NET platform -- functional idioms (immutability by default, pattern matching, function composition) are its natural style, while still fully supporting object-oriented code and interoperating seamlessly with the broader .NET/C# ecosystem.

Immutability by Default

let x = 5
// x <- 6  -- compile error, x is immutable by default

let mutable y = 5
y <- 6  // explicit opt-in required to allow reassignment

Discriminated Unions & Exhaustive Pattern Matching

// A Shape is EXACTLY one of these -- the type system precisely
// expresses which possibilities are actually valid
type Shape =
    | Circle of float
    | Rectangle of float * float
    | Triangle of float * float

let area shape =
    match shape with
    | Circle r -> System.Math.PI * r * r
    | Rectangle (w, h) -> w * h
    | Triangle (b, h) -> 0.5 * b * h
// Compiler warns if a new case (e.g. Square) is added but not
// handled here -- catches a class of bug an if/else chain might miss

Option: No More Null Reference Errors

let tryFindUser (id: int) : User option =
    // returns Some user or None
    ...

// Caller MUST handle both cases -- compiler enforces it
match tryFindUser 5 with
| Some user -> printfn "Found: %s" user.Name
| None -> printfn "Not found"

Record Types

type Person = { Name: string; Age: int }

let alice = { Name = "Alice"; Age = 30 }

// Structural equality generated automatically -- no manual
// Equals() override needed, unlike an equivalent C# class
{ Name = "Alice"; Age = 30 } = alice  // true

Type Inference

// No explicit type annotations needed -- compiler infers int -> int -> int
// from how + is used, while still being fully statically type-checked
let add x y = x + y

Keep your own version of these notes — editable, searchable, and organised by your stack.

Start free