f# - Check several option types and then convert to type -


i new programmer in general, , f#. i've ran particular problem several times, , have yet solve efficiently in opinion. here problem:

i have these example types:

 type retail1 = | fashion | auto | sports  type wholesale1 = | fashion | auto | sports  type events1 = | wedding | birthday    type product =        | retail of retail1 | wholesale of wholesale1 | events of events1       | noproduct 

i want convert possibility of first 3 types product type via function:

 let converttoproduct (retail: retail1 option)        (wholesale: wholesale1   option) (events: events1 option) =       // convert product here       if retail.issome retail retail       elif wholesale.issome wholsale wholseale       elif events.issome events events       else noproduct 

the way have handled in pass chain long if elif statement check each condition , return final type of product, not feel correct, or @ least idiomatic f#. recommended approach problem?

how this:

let converttoproduct (retail: retail1 option) (wholesale: wholesale1 option) (events: events1 option) =     match (retail, wholesale, events)     |some rt, none, none -> retail rt     |none, wh, none -> wholesale wh     |none, none, ev -> events ev     |_ -> noproduct 

this exploits fact if convert arguments tuple, can pretty concise pattern matching on result.

pattern matching extremely powerful, can find more details types of pattern matching can perform in msdn documentation.


Popular posts from this blog

php - How should I create my API for mobile applications (Needs Authentication) -

5 Reasons to Blog Anonymously (and 5 Reasons Not To)

Google AdWords and AdSense - A Dynamic Small Business Marketing Duo