基本歧视联合使用

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