F#中的递归记录 [英] Recursive records in F#

查看:78
本文介绍了F#中的递归记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我和一个朋友正在阅读F#,此刻正在乱搞记录.

A friend and I are reading up on F# and are messing around with records at the moment.

我们已经记录了以下代表人的记录:

We have made the following record for representing a person:

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

F#Interactive接受它,并且在某种程度上,该类型有意义,但我们看不到如何使用它.当我们尝试声明一个人时,我们必须在声明时声明父母,然后依次声明其父母,依此类推.有什么方法可以实际使用此类型?如果没有,我们怎么能创建它呢?

F# Interactive accepts it, and in some way, the type makes sense, except we can't see how to use it. 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:我们很清楚,由于父母本意是可选的,所以我们应该使用选项(某些x |无)将它们封装起来.

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中已经编写了一个解决方案. 我的问题是,我是否可以实际使用上述类型,例如申报上述表格的个人记录?如果没有,我肯定做了一个无法使用的类型.为什么我要做这样的类型?

My question is not how to fix the above, a solution is already written in the PS. My question is, can I actually use the above type, e.g. 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显示了一个更有用的定义,但是您可以创建您的Person类型的实例:

Lee shows a more useful definition, but you can create an instance of your Person type:

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

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.

这篇关于F#中的递归记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆