3

我有两条具有父子关系的记录:

type Parent = 
  { Number: int
    Child: Child }
and Child = 
  { String: string
    Parent: Parent }

我尝试使用以下语法初始化这些,但不起作用:

let rec parent = 
  { Number = 1
    Child = child }
and child = 
  { String = "a"
    Parent = parent }

这将导致

parent : Parent = { Number = 1
                    Child = null }
child : Child = { String = "a";
                  Parent = { Number = 1 
                             Child = null } }

如何在不依赖可变字段或事后复制和更新的情况下初始化这些with

4

1 回答 1

3

这是初始化它的语法:

let rec parent = 
  { Number = 1
    Child = 
      { String = "a"
        Parent = parent } 
  }

结果是:

parent : Parent = { Number = 1
                    Child = { String = "a"
                              Parent = ... } }

请注意,如本答案中所述,此语法可能比有意的更意外,并且仅适用于简单的自引用(例如,将递归值传递给函数)。

于 2018-03-20T07:39:01.440 回答