F # Discriminatory Union - “downgrade” to subtype

I really don't know what the correct title should be for this question, but:

I have a discriminatory union called MyDiscriminatedUnionin F#:

type MyDiscriminatedUnion =
| Foo of Foo
| Bar of Bar

where Fooand Barare the types of records:

type Foo = {
   ... }
type Bar = {
   ... }

I created a union type value Foo:

let foo = Foo {
   ... }

The compiler tells me that foo is of type MyDiscriminatedUnion.

Then I want to pass foo to a function that expects type Foo, not MyDiscriminatedUnion. Therefore, the compiler complains. How to tell the compiler what the Footype is Foo?

I tried:

let foo:Foo 

when constructing a union type value.

I tried to omit foo in Foo:

foo :?> MyDiscriminatedUnion.Foo

but none of them work.

Please, help.

+4
source share
2

OO: . , , , , , :

type MyDiscriminatedUnion =
  | Its_a_Foo of Foo
  | Its_a_Bar of Bar

Its_a_Foo Its_a_Bar , . MyDiscriminatedUnion Its_a_Foo, Foo, Its_a_Bar, Bar. , , .

// The function that takes a record of type Foo as argument
let f (x: Foo) = ...

// Our value of type MyDiscriminatedUnion
let myDU = Its_a_Foo { ... }

// Extracting the Foo and passing it to f
match myDU with
| Its_a_Foo foo -> f foo
| Its_a_Bar bar -> // What should we do if it an Its_a_Bar instead?

// If you're _really_ certain that myDU is Its_a_Foo { ... }, not Its_a_Bar { ... }
// you can do this. If it Its_a_Bar, you will get an error.
let (Its_a_Foo foo) = myDU
f foo
+8

...

:

let MapToSubtype subtype =
   match subtype with
   | Foo foo -> foo

:

let x = MapToSubtype foo

... .

: : JustSomeFSharpGuy , MapToSubtype , , - , Foo.

, :

let MapToSubtype subtype =
    match subtype with
    | Foo foo -> foo
    | _ -> // deal with exception here
0

All Articles