Recursive records in F #

A friend and I read on F # and are currently messing with the records.

We made the following entry to represent the person:

type Person = {name: string; father: Person; mother: Person;} 

F # Interactive accepts it, and in some way the type makes sense, except that we cannot see how to use it. When we try to declare a person, we must declare the parents at the time of the announcement and, in turn, declare the parents and so on. Is there any way to use this type? And if not, then why can we even create it?

PS: We well know that since parents must be optional, we had to encapsulate them using the (Some x | None) option.

EDIT

My question is not how to fix this, the solution is already written in PS. My question is: can I use the above type for example? declare the person of the above form? If not, I should have made an unsuitable type. Why can I make this type?

+4
source share
2 answers

Lee shows a more useful definition, but you can instantiate your Person type:

 let rec loopy = { name = "loopy"; father = loopy; mother = loopy } 

or

 let rec male = { name = "male"; father = male; mother = female } and female = { name = "female"; father = male; mother = female} 

Of course, this is not entirely useful if you are modeling real people, but the compiler does not know this. A similar recursive type can be useful if you are trying to define a loop, for example.

+10
source

If you declare father and mother as a Parent option , you can use it as:

 let f = { name = "Father"; father = None; mother = None } let m = { name = "Mother"; father = None; mother = None } let c = { name = "Child"; father = Some(f); mother = Some(m) } 

without using the Parent option for father and mother you need to create an instance of "null parent" and use it instead of None .

+8
source

Source: https://habr.com/ru/post/1485097/


All Articles