简体   繁体   English

F#中的递归记录

[英]Recursive records in F#

A friend and I are reading up on F# and are messing around with records at the moment. 我和朋友正在读F#,目前正在搞乱记录。

We have made the following record for representing a person: 我们为代表一个人做了以下记录:

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

F# Interactive accepts it, and in some way, the type makes sense, except we can't see how to use it. F#Interactive接受它,并且在某种程度上,类型是有意义的,除了我们看不到如何使用它。 When we try to declare a person, we have to declare the parents at the point of declaration, and in turn declare their parents and so on. 当我们试图宣布一个人时,我们必须在声明点声明父母,然后再声明他们的父母等等。 Is there any way to actually use this type? 有没有办法真正使用这种类型? And if not, how come we are even able create it? 如果没有,我们怎么能创造它呢?

PS: We are well aware that since parents are intended to be optional, we should have encapsulated them with the option (Some x | None) type. PS:我们很清楚,由于父项是可选的,我们应该用选项(Some x | None)类型封装它们。

EDIT 编辑

My question is not how to fix the above, a solution is already written in the PS. 我的问题不是如何解决上述问题,已经在PS中编写了一个解决方案。 My question is, can I actually use the above type, eg declare a Person record of the above form? 我的问题是,我可以实际使用上述类型,例如声明上述表格的人事记录吗? If not, I must have made an unusable type. 如果没有,我必须做一个无法使用的类型。 Why can I make such a type? 为什么我可以制作这样的类型?

Lee shows a more useful definition, but you can create an instance of your Person type: Lee显示了一个更有用的定义,但您可以创建Person类型的实例:

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, these aren't at all helpful if you're modeling real people, but the compiler doesn't know that. 当然,如果你对真实的人进行建模,这些并没有任何帮助,但编译器并不知道。 A similar recursive type could be useful if you're trying to define a cycle, for instance. 例如,如果您尝试定义循环,则类似的递归类型可能很有用。

If you declare father and mother as Parent option then you can use it like: 如果您将fathermother声明father Parent option那么您可以使用它:

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 Parent option for father and mother you would have to create a "null parent" instance and use that instead of None . 如果不为fathermother使用Parent option ,则必须创建“null parent”实例并使用它而不是None

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM