सामग्री पर जाएँ

लेसन 21 · Types, Records and Unions

Discriminated Unions

Learn F# discriminated unions: cases with data, single-case wrappers, recursive types, struct unions, how they differ from enums, and how to model real domains so invalid states cannot exist.

A record says "this AND that": a person has a name and an age. A discriminated union says "this OR that": a shape is a circle or a rectangle, a payment is cash, card or invoice. Unions are the feature that most F# programmers miss when they go back to other languages, because they let you describe a closed set of possibilities and have the compiler check that every one is handled.

Your first union

FSHARP
type Shape =
    | Circle of radius: float
    | Rectangle of width: float * height: float
    | Point

let area shape =
    match shape with
    | Circle r -> System.Math.PI * r * r
    | Rectangle (w, h) -> w * h
    | Point -> 0.0

printfn "%.2f" (area (Rectangle (3.0, 4.0)))   // 12.00

Each line after | is a case. A case may carry data (Circle of radius: float), several values (Rectangle of width: float * height: float) or nothing (Point). The labels radius, width and height are optional but make the code and tooling messages much clearer. A value of type Shape is exactly one case at a time, and match takes it apart.

The match is checked for completeness. If you add | Triangle of ... later, every match that forgets it produces a warning pointing at the exact line. That is the big win: changing a model lights up everything affected.

Why not an enum or a class hierarchy?

An F# enum is just a named integer (type Color = Red = 0 | Green = 1). It cannot carry data and the compiler cannot prove that a match is complete, because any integer can be cast to it. A union cannot hold an invalid case and each case has its own data.

A class hierarchy can model the same thing, but it spreads the logic: to add a new operation you edit every class. With a union the cases are fixed in one place and operations are ordinary functions, so adding an operation is easy and adding a case is guided by warnings.

C# C# stand-in: the same idea with a record hierarchy and a switch

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Notice the extra _ case: C# cannot know the hierarchy is closed, F# can.

Modelling a domain

Unions shine when you model rules directly in types. Compare a "stringly" design with a union:

FSHARP
type PaymentMethod =
    | Cash
    | Card of number: string * expiry: string
    | Invoice of customerId: int

let describe method =
    match method with
    | Cash -> "paid in cash"
    | Card (number, _) -> $"card ending {number.[number.Length - 4 ..]}"
    | Invoice id -> $"invoice for customer {id}"

An Invoice never has a card number and a Card never has a customer id. In a class with Number: string and CustomerId: int fields you would have to remember which fields are valid for which kind, and nothing would stop a mix-up. The union makes illegal states unrepresentable, a phrase you will hear often in F# circles.

Single-case unions

A union with one case is a cheap way to give a primitive a distinct type:

FSHARP
type CustomerId = CustomerId of int
type OrderId = OrderId of int

let loadOrder (OrderId id) = $"loading order {id}"

let c = CustomerId 7
// loadOrder c   // compile error: expected OrderId

You cannot pass a customer id where an order id is expected, even though both wrap an int. The pattern (OrderId id) in the parameter unwraps it. A single-case union costs one small object; mark it [<Struct>] to avoid that allocation.

Recursive unions

A union may refer to itself, which is the natural way to describe trees and expressions:

FSHARP
type Expr =
    | Num of float
    | Add of Expr * Expr
    | Mul of Expr * Expr

let rec eval e =
    match e with
    | Num n -> n
    | Add (a, b) -> eval a + eval b
    | Mul (a, b) -> eval a * eval b

eval (Add (Num 2.0, Mul (Num 3.0, Num 4.0)))   // 14.0

The function has to be marked rec because it calls itself. Expression trees like this are the heart of interpreters and compilers; you will build a larger one in the expression evaluator project.

flowchart TD
    A["Add"] --> B["Num 2"]
    A --> C["Mul"]
    C --> D["Num 3"]
    C --> E["Num 4"]

The value Add (Num 2.0, Mul (Num 3.0, Num 4.0)) as a tree. eval walks it from the root.

C# C# stand-in: evaluating the same tree

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Generic unions and members

Unions can take type parameters. The built-in Option and Result types are exactly this (see Option and ValueOption):

FSHARP
type Tree<'T> =
    | Leaf
    | Node of left: Tree<'T> * value: 'T * right: Tree<'T>

type Shape with
    member this.IsRound =
        match this with
        | Circle _ -> true
        | _ -> false

Like records, unions have structural equality and comparison, print nicely with %A, and may be marked [<Struct>]. A struct union with several cases must give every field a unique name.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What does a discriminated union express?

    Records are AND-types, unions are OR-types: exactly one case is present at a time.
  2. 2. What happens when you add a new case and a match does not handle it?

    Pattern matches over unions are checked for completeness, which is why changing a model is safe.
  3. 3. Why wrap an int in a single-case union such as OrderId?

    The wrapper creates a distinct type, so passing a CustomerId where an OrderId is expected does not compile.
  4. 4. Why must eval in the Expr example be declared with let rec?

    A function can refer to itself only if declared with rec.

Summary

  • A union lists the cases a value can take; each case may carry data.
  • match over a union is checked for completeness, so model changes are guided by the compiler.
  • Unions beat enums and class hierarchies for closed sets of alternatives.
  • Single-case unions give primitives distinct meaning; recursive unions describe trees and expressions.
  • Unions support generics, members, structural equality and [<Struct>].

Next: Units of Measure and Type Abbreviations

अपनी प्रगति ट्रैक करें

मुफ़्त अकाउंट बनाएँ, लेसन पूरे के रूप में चिह्नित करें और किसी भी डिवाइस पर वहीं से शुरू करें जहाँ छोड़ा था।