基本歧視聯合使用

F#中的歧視聯合提供了一種定義可以包含任意數量的不同資料型別的型別的方法。它們的功能類似於 C++聯合或 VB 變體,但具有型別安全的額外好處。

// define a discriminated union that can hold either a float or a string
type numOrString = 
    | F of float
    | S of string

let str = S "hi" // use the S constructor to create a string
let fl = F 3.5 // use the F constructor to create a float

// you can use pattern matching to deconstruct each type
let whatType x = 
    match x with
        | F f -> printfn "%f is a float" f
        | S s -> printfn "%s is a string" s

whatType str // hi is a string
whatType fl // 3.500000 is a float