2017-06-22 38 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表達式。

相關問題