Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize mutually recursive records in F# [duplicate]

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?

like image 483
cmeeren Avatar asked Oct 25 '25 05:10

cmeeren


1 Answers

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).

like image 132
cmeeren Avatar answered Oct 26 '25 23:10

cmeeren