我有一个数据管道,其中每一步都需要更多数据字段。我想通过尊重不变性以功能性的方式做到这一点。我可以通过一堂课来实现这一点,我想知道是否有 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。
我认为这对于 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)