Search code examples
.netf#polymorphismrecordsmultimethod

F# Polymorphism


Are there any ways to deal with polymorphism in F# with regards to record types?

Just to give an example, lets say we have two record types of addresses , street address and box address. I figure that one can deal with them in patternmatching when it comes to behaviour. but what about referencing, is there any way to reference (not meaning object ref) both types from other records


Solution

  • If I understand correctly your question, I'd use a discriminated union:

    type StreetAddress = {. . . }
    type BoxAddress = {. . .}
    
    type Address =
      | StreetAddress of StreetAddress
      | BoxAddress of BoxAddress
    

    and then you can create and reference Address values.

    If street and box address share some common data you could put it into a separate BaseAddress record type, that is then used inside StreetAddress and BoxAddress, or used directly by Address:

    type BaseAddress = {. . . }
    type StreetAddress = {. . . }
    type BoxAddress = {. . .}
    
    type Address =
      | StreetAddress of BaseAddress*StreetAddress
      | BoxAddress of BaseAddress*BoxAddress