Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursion & Immutability in F#

Tags:

recursion

f#

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?

like image 993
eirik Avatar asked Feb 12 '14 20:02

eirik


People also ask

What recursion means?

Recursion means "defining a problem in terms of itself". This can be a very powerful tool in writing algorithms. Recursion comes directly from Mathematics, where there are many examples of expressions written in terms of themselves. For example, the Fibonacci sequence is defined as: F(i) = F(i-1) + F(i-2)

What is recursion in programming?

Recursion means “solving a problem using the solution of smaller subproblems (smaller version of the same problem)” or “defining a problem in terms of itself”. This is a widely used idea in data structures and algorithms to solve complex problems by breaking them down into simpler ones.

What is recursion in linguistics with example?

"In English, recursion is often used to create expressions that modify or change the meaning of one of the elements of the sentence. For example, to take the word nails and give it a more specific meaning, we could use an object relative clause such as that Dan bought, as in.

What is a recursion method?

Recursion is the technique of making a function call itself. This technique provides a way to break complicated problems down into simple problems which are easier to solve. Recursion may be a bit difficult to understand. The best way to figure out how it works is to experiment with it.


1 Answers

let rec mkChild i = {Value = i; Parent = parent}
and parent = { Children = children }
and children = List.init length mkChild
like image 61
desco Avatar answered Oct 26 '22 00:10

desco