简体   繁体   中英

Syntax: In F# how to return a value from a member of a discriminated union?

With the following code:

type ContactDetail = { Name: string; Content: string; Text: string }
type Internet      = { Name: string; Content: string; Text: string }
type PhoneNumber   = { Name: string; Content: string; Text: string }
type Address       = { Name: string; Content: string; Text: string }

    module FrontOffice =    
        type Details =
            | ContactDetail of ContactDetail * Id: Guid
            | Internet      of Internet   * Id: Guid
            | PhoneNumber   of PhoneNumber   * Id: Guid
            | Address       of Address  * Id: Guid
            
          
            member this.name = 
                match this with
                | ContactDetail(_, id)
                | Internet(_, id) 
                | PhoneNumber(_, id) 
                | Address(_, id) -> ???????????????????

I need the extension method, this.name, to return the Name property on the match. How is this done?

TIA

This is how:

type ContactDetail = { Name: string; Content: string; Text: string }
type Internet      = { Name: string; Content: string; Text: string }
type PhoneNumber   = { Name: string; Content: string; Text: string }
type Address       = { Name: string; Content: string; Text: string }

module FrontOffice =

    type Details =
        | ContactDetail of ContactDetail * Id: Guid
        | Internet      of Internet   * Id: Guid
        | PhoneNumber   of PhoneNumber   * Id: Guid
        | Address       of Address  * Id: Guid
        
        member this.name = 
            match this with
            | ContactDetail (cd, _) -> cd.Name
            | Internet (i, _) -> i.Name
            | PhoneNumber (pn, _) -> pn.Name
            | Address (a, _) -> a.Name

    let sample () =
        let contactDetail = { ContactDetail.Name = "myname"; Content = "mycontent"; Text = "mytext" }
        let details: Details = ContactDetail (contactDetail, Guid.NewGuid ())
        printfn "%A" details
        // ContactDetail ({Name = "myname"; Content = "mycontent"; Text = "mytext";},1a25bcdd-76b0-4cb3-8a34-72872d2542c2)
        printfn "The name is %s" details.name
        // The name is myname

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM