7

我试图了解受歧视的工会和记录类型;特别是如何组合它们以获得最大的可读性。这是一个例子 - 假设一个运动队可以有积分(联赛积分和净胜球),或者它可以被停赛,在这种情况下它没有积分或净胜球。以下是我试图表达的方式:

type Points = { LeaguePoints : int; GoalDifference : int }

type TeamState = 
    | CurrentPoints of Points
    | Suspended

type Team = { Name : string; State : TeamState }

let points = { LeaguePoints = 20; GoalDifference = 3 }

let portsmouth = { Name = "Portsmouth"; State = points }

问题出现在最后一行的末尾,我说“State = points”。我得到“表达式应该有 TeamState 类型,但这里有 Points 类型”。我该如何解决?

4

2 回答 2

16

要为 pad 的答案添加一些细节,您的初始版本不起作用的原因是分配给的State值的类型应该是 type 的可区分联合值TeamState。在你的表达中:

let portsmouth = { Name = "Portsmouth"; State = points }

...的类型pointsPoints。在 pad 发布的版本中,表达式CurrentPoints points使用构造函数TeamState来创建一个可区分的联合值,表示CurrentPoints. union 为您提供的另一个选项是Suspended,可以这样使用:

let portsmouth = { Name = "Portsmouth"; State = CurrentPoints points }
let portsmouth = { Name = "Portsmouth"; State = Suspended }

如果你没有使用构造函数的名称,那么你将如何构造一个暂停的团队是不清楚的!

最后,您还可以将所有内容都写在一行上,但这不那么可读:

let portsmouth = 
  { Name = "Portsmouth"
    State = CurrentPoints { LeaguePoints = 20; GoalDifference = 3 } }
于 2012-04-12T16:12:55.447 回答
6
let portsmouth = { Name = "Portsmouth"; State = CurrentPoints points }
于 2012-04-12T16:02:31.020 回答