3

关于记录类型,有什么方法可以处理 F# 中的多态性?

举个例子,假设我们有两种地址记录类型,街道地址和邮箱地址。我认为在行为方面可以通过模式匹配来处理它们。但是引用呢,有什么方法可以从其他记录中引用(不是指对象引用)这两种类型

4

2 回答 2

10

如果我正确理解您的问题,我会使用有区别的工会:

type StreetAddress = {. . . }
type BoxAddress = {. . .}

type Address =
  | StreetAddress of StreetAddress
  | BoxAddress of BoxAddress

and then you can create and reference Address values.

If street and box address share some common data you could put it into a separate BaseAddress record type, that is then used inside StreetAddress and BoxAddress, or used directly by Address:

type BaseAddress = {. . . }
type StreetAddress = {. . . }
type BoxAddress = {. . .}

type Address =
  | StreetAddress of BaseAddress*StreetAddress
  | BoxAddress of BaseAddress*BoxAddress
于 2012-07-12T12:07:59.693 回答
-2

所以我认为你希望能够创造出类似的东西

type A = {aval:int;b:B}
and B = {bval:int;a:A}

现在这个定义可以很好地编译,但是您将无法实际创建它,因为记录是常量并且您无法创建所需的递归结构。然而,像

type A = {aval:int;b:B option}
and B = {bval:int;a:A option}

实际上可以创建并且可能是您想要的

于 2012-07-12T11:26:12.603 回答