Recursion & Immutability in F#

f#, recursion

Solution

let rec mkChild i = {Value = i; Parent = parent}
and parent = { Children = children }
and children = List.init length mkChild

Problem

Consider the following simplistic example: ``` type Parent = { Children : Child list } and Child = { Value : int ; Parent : Parent } let rec children = [ { Value = 0 ; Parent = parent } ] and parent = { Children = children } ``` The F# compiler is smart enough to correctly initialize these recursive objects, as can be verified by running ``` obj.ReferenceEquals(parent, parent.Children.Head.Parent) ``` Now, consider the following generalization: ``` let length = 100 // assume arbitrary let rec children = List.init length (fun i -> { Value = i ; Parent = parent }) and parent = { Children = children } ``` This definition will result in a compiler error. My question is the following: is there any way I could make the above binding without resorting to reflection or mutable fields?

Original source