如何解开没有模式匹配的歧视联盟?

use*_*180 4 f#

我有一个像这样的歧视联盟:

Type Result =
| Good of bool | Bad of bool
Run Code Online (Sandbox Code Playgroud)

在许多情况下,我知道结果是好的.要打开结果,我必须使用模式匹配仅适用于Good选项.结果我收到一条警告(不是错误),上面写着"此表达式上的模式匹配不完整......".有没有办法解开,而不必使用模式匹配?

The*_*ght 8

你可以使用let,例如

type Result =
    | Good of bool 
    | Bad of bool

let example = Good true

let (Good unwrappedBool) = example
Run Code Online (Sandbox Code Playgroud)

请注意,这仍然会导致编译器警告匹配情况可能不完整.

但从技术上讲,这仍然是使用模式匹配,只是在没有match表达式的情况下这样做.


mon*_*res 6

您可以像其他任何类型一样向联合添加方法,如下所示:

type Result =
    | Good of bool
    | Bad of bool
    with
        member x.GoodValue =
            match x with
            | Good b -> b
            | Bad _ -> failwith "Not a good value"

[<EntryPoint>]
let main argv = 

    let r = Good true
    let s = Bad true

    printfn "%A" r.GoodValue
    printfn "%A" s.GoodValue // You know what happens..!

    0
Run Code Online (Sandbox Code Playgroud)