Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unwrap a discriminated union without pattern matching?

Tags:

f#

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?

like image 641
user3587180 Avatar asked Jun 22 '17 04:06

user3587180


People also ask

How is a discriminated union defined?

A discriminated union is a union data structure that holds various objects, with one of the objects identified directly by a discriminant. The discriminant is the first item to be serialized or deserialized. A discriminated union includes both a discriminant and a component.

When to use discriminated union?

Discriminated unions are useful for heterogeneous data; data that can have special cases, including valid and error cases; data that varies in type from one instance to another; and as an alternative for small object hierarchies.


1 Answers

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.

like image 71
TheInnerLight Avatar answered Nov 01 '22 06:11

TheInnerLight