Step 1 of 4 · Reading · ~1 min
Learn
Pattern Matching and Types
Discriminated unions (DUs) define a type that's one of several variants. F#'s killer type-modeling feature.
type Shape =
| Circle of radius: float
| Square of side: float
| Rectangle of width: float * height: float
let area s =
match s with
| Circle r -> System.Math.PI * r * r
| Square s -> s * s
| Rectangle (w, h) -> w * h
let shapes = [Circle 5.0; Square 4.0; Rectangle (3.0, 6.0)]
shapes |> List.iter (fun s -> printfn "%f" (area s))
DUs are how you eliminate null checks:
type MyOption<'T> =
| Present of 'T
| Absent
Give the cases fresh names like this: writing your own Some/None shadows the built-in ones for the rest of the file, and the errors that follow are baffling.
F#'s built-in option type works exactly this way. Pattern match on Some x to extract the value safely; None is the explicit absent case. The compiler forces you to handle both — no NullReferenceException possible.
Up nextLists and RecursionLists, Recursion, IO
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…