F# 如何在没有模式匹配的情况下展开有区别的并集?

F# 如何在没有模式匹配的情况下展开有区别的并集?,f#,F#,我有这样一个受歧视的联盟: Type Result = | Good of bool | Bad of bool type Result = | Good of bool | Bad of bool with member x.GoodValue = match x with | Good b -> b | Bad _ -> failwith "Not a good va

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

Type Result =
| Good of bool | Bad of bool
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

在很多情况下,我知道结果是好的。要打开结果,我必须使用模式匹配作为好的选择。结果,我得到一个警告(不是错误),上面写着“此表达式上的模式匹配不完整…”。有没有一种方法不必使用模式匹配就可以打开Is?

您可以使用
let
,例如

type Result =
    | Good of bool 
    | Bad of bool

let example = Good true

let (Good unwrappedBool) = example
请注意,这仍然会导致编译器警告匹配案例可能不完整


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

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

Type Result =
| Good of bool | Bad of bool
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
类型结果=
|好的,布尔
|布尔的坏消息
具有
成员x.GoodValue=
将x与
|好的b->b
|错误->失败,带有“不好的值”
[]
让主argv=
让r=好的真值
让s=坏的真的
printfn“%A”r.GoodValue
printfn“%A”s.GoodValue//你知道会发生什么事。。!
0

如果在许多情况下,您知道结果是
好的
,我会重新考虑设计,而不是一直“铸造”到
好的
。另一种说法是:如果结果总是
好的
,而从不
坏的
,为什么要返回一个可能是两者之一的类型?直接返回Good包装的任何值。评级最高的答案建议引入潜在的运行时故障,这实际上是最后的选择。