Extending a record type with another record type in F#
Asked Answered
M

1

8

I have two record types:

type Employee = {
        Id:          string
        Name:        string
        Phone:       string
}
    
type AuditLog = {
    PerformedBy: string
    PerformedOn: string
}

Following are instances of the record types:

let emp = {
    Id = "123"
    Name = "Abc"
    Phone = "999"
}

let log = {
    PerformedBy = "234"
    PerformedOn = "1/1/1"
}

Is there any way to combine the fields of these two instances to create a new record/anonymous record type like the following?

let combined = {
    Id = "123"
    Name = "Abc"
    Phone = "999"
    PerformedBy = "234"
    PerformedOn = "1/1/1"
}
Mournful answered 9/5, 2021 at 7:46 Comment(2)
learn.microsoft.com/en-us/dotnet/fsharp/language-reference/…Inhalant
You can search "F# record inherit" here on SO for a great number of answers revolving around this.Pet
P
8

In F# record types are not inheritable or combineable in other ways. The only thing you can do to get a type with the combined fields is

  1. to explicitly create a new record that has no relation to the existing 2 types

  2. create such type anonymously, @JL0PD pointed to the docs for anonmyous types. Anonymous types can be very helpful in some situations, but explicit types are the better choice - make code more readable - in most situations.

  3. create a record that has 2 fields with the 2 types, which is not really what you are looking for.

Some languages like Typescript have intersection types where you can define a type as having the fields of a set of other types (since the fields of the created type are the union of the combined types, "intersection" sounds strange for my taste). I guess you are looking for that, but that is not available in F# and most languages.

Pastypat answered 9/5, 2021 at 9:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.