在 F# 中使用另一种记录类型扩展记录类型 [英] Extending a record type with another record type in F#

查看:72
本文介绍了在 F# 中使用另一种记录类型扩展记录类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两种记录类型:

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"
}

推荐答案

在 F# 中,记录类型不可继承或以其他方式组合.你唯一能做的就是获得带有组合字段的类型

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. 显式创建一个新记录,与现有的 2 种类型无关

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

创建这样的类型匿名,@JL0PD 指向匿名类型的文档.匿名类型在某些情况下非常有用,但在大多数情况下,显式类型是更好的选择 - 使代码更具可读性.

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.

创建一个包含 2 个字段和 2 种类型的记录,这不是您真正要查找的内容.

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

像 Typescript 这样的一些语言具有交集类型,您可以在其中将类型定义为具有一组其他类型的字段(因为创建的类型的字段是 union 在组合类型中,intersection"对我来说听起来很奇怪).我猜您正在寻找它,但它在 F# 和大多数语言中不可用.

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.

这篇关于在 F# 中使用另一种记录类型扩展记录类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆