F# Discriminated Union - "downcasting" to subtype -


i don't know proper title question should be, but:

i have discriminated union called mydiscriminatedunion in f#:

type mydiscriminatedunion = | foo of foo | bar of bar 

where foo , bar record types:

type foo = {    ... } type bar = {    ... } 

i created value of union type foo:

let foo = foo {    ... } 

the compiler tells me foo of type mydiscriminatedunion.

then want pass foo function expects type foo, not mydiscriminatedunion. therefore compiler complains. how tell compiler foo of type foo?

i have tried:

let foo:foo  

when constructing value of union type.

i have tried "downcast" foo foo by:

foo :?> mydiscriminatedunion.foo 

but neither of them work.

please help.

this common mistake when coming oo language: there no subtypes involved in code. fact named union cases same type of field contain can make confusing though, let me give different example:

type mydiscriminatedunion =   | its_a_foo of foo   | its_a_bar of bar 

its_a_foo , its_a_bar not subtypes, they're union cases. value of type mydiscriminatedunion either its_a_foo, in case has field of type foo, or its_a_bar, in case has field of type bar. know 1 , corresponding field, need use pattern matching.

// function takes record of type foo argument let f (x: foo) = ...  // our value of type mydiscriminatedunion let mydu = its_a_foo { ... }  // extracting foo , passing f match mydu | its_a_foo foo -> f foo | its_a_bar bar -> // should if it's its_a_bar instead?  // if you're _really_ mydu its_a_foo { ... }, not its_a_bar { ... } // can this. if it's its_a_bar, error. let (its_a_foo foo) = mydu f foo 

Comments

Popular posts from this blog

javascript - Google App Script ContentService downloadAsFile not working -

javascript - Function overwritting -

php - Find a regex to take part of Email -