使用附加字段扩展记录

Geh*_*len 4 f#

我有一个数据管道,其中每一步都需要更多数据字段。我想通过尊重不变性以功能性的方式做到这一点。我可以通过一堂课来实现这一点,我想知道是否有 F# 方法可以做到这一点?

// code that loads initial field information and returns record A

type recordA = {
    A: int
}

// code that loads additional field information and returns record AB

type recordAB = {
    A: int
    B: int
}

// code that loads additional field information and returns record ABC

type recordABC = {
    A: int
    B: int
    C: int
}

Run Code Online (Sandbox Code Playgroud)

由于记录是密封的,我不能继承它们。如何避免必须使用与上一步完全相同的字段定义新记录并添加所需字段?最好我希望有一条记录,其中包含所有必填字段,并且这些字段在每个步骤中都分配给它们的值。

请注意,每个步骤中添加的字段数量可能超过 1。

Jus*_*mer 7

我认为这对于 F# 中最近引入的匿名记录来说是一个很好的用例。

let a = {| X = 3 |}
let b = {| a with Y = "1"; Z = 4.0|}
let c = {| b with W = 1 |}
printfn "%d, %s, %f, %d" c.X c.Y c.Z c.W
Run Code Online (Sandbox Code Playgroud)

  • @Gehaktmolen 实际上,在这种情况下,您不必单独定义记录或在它们之间复制数据。这个答案使用匿名记录,在使用它们之前不必定义它们,并且它使用“copy-with-update”语法“let b = {|a with Y = 2|}”来复制一条记录绑定为“a”,并另外设置“Y”的值,创建一个绑定到标识符“b”的新实例。 (2认同)
  • 遗憾的是,该项目仍在旧版本的 F# 上,我无法使用此功能:(。它本来可以实现我想要做的事情。 (2认同)