2017-06-22 78 views
2

我有一个区分联合是这样的:如何在没有模式匹配的情况下打开歧视联盟?

Type Result = 
| Good of bool | Bad of bool 

在许多情况下,我知道结果是好的。为了解开结果,我必须使用模式匹配来选择好的选项。因此,我得到一个警告(不是错误),表示“此表达式上的模式匹配不完整..”。有没有办法解开是不需要使用模式匹配?

+3

如果,在很多情况下,你知道结果是'Good'我会重新考虑设计,而不是“铸造'一直到'好'。 – CaringDev

+1

另一种说法是:如果结果总是“好的”而不是“坏的”,为什么要返回一种类型可能是?直接返回Good包装的任何值。评分最高的答案建议引入潜在的运行时间故障,这真是最后的选择。 – Asik

回答

4

您可以添加方法,以工会就像任何其他类型的,像这样:

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 
6

您可以使用let,例如,

type Result = 
    | Good of bool 
    | Bad of bool 

let example = Good true 

let (Good unwrappedBool) = example 

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

但是,从技术上讲,这仍然是使用模式匹配,只是这样做没有match表达式。

相关问题