4

I have two records that have a parent-child relationship:

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

I have tried initializing these using the following syntax, which doesn't work:

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

this leads to

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

How to I initialize these without relying on mutable fields or copy-and-update after the fact using with?

cmeeren
  • 3,890
  • 2
  • 20
  • 50
  • Why `Child` is `null` for `parent` variable? Shouldn't it have the value of the `child` variable? The `and` keyword's work is to declare both variables (`parent` and `child`) together so one can reference another. So why the `null` value? – gdyrrahitis Jun 20 '18 at 11:34

1 Answers1

3

Here's the syntax to initialize it:

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

The result is:

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

Note that as described in this answer, this syntax may be more accidental than intentional, and will not work for more than simple self-references (e.g. passing the recursive value into a function).

cmeeren
  • 3,890
  • 2
  • 20
  • 50