5
votes

I have a discriminated union like this:

Type Result =
| Good of bool | Bad of bool

In many cases I know that result is Good. To unwrap the Result, I have to use pattern matching for just the Good option. As a result I get a warning (not an error) that says "Incomplete pattern match on this expression..". Is there a way to unwrap is without having to use pattern matching?

2
If, in many cases, you know that the result is Good I'd reconsider the design instead of 'casting' to Good all the time.CaringDev
Another way to put it: if the result is always Good and never Bad, why return a type that could be either? Just return whatever value is wrapped by Good directly. The top-rated answer suggests introducing potential run-time failures and that's really a last-resort option.Asik

2 Answers

7
votes

You can add methods to unions just like any other type, like this:

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
9
votes

You can just use let, e.g.

type Result =
    | Good of bool 
    | Bad of bool

let example = Good true

let (Good unwrappedBool) = example

Note that this will still result in a compiler warning that the match cases might be incomplete.

Technically, however, this is still using pattern matching, just doing so without a match expression.