将受歧视的联盟与记录类型相结合

时间:2012-04-12 15:59:51

标签: f#

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

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,但这里有类型点'。我该如何解决这个问题?

2 个答案:

答案 0 :(得分:16)

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

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

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

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

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

最后,您还可以只在一行中编写所有内容,但这不是可读的:

let portsmouth = 
  { Name = "Portsmouth"
    State = CurrentPoints { LeaguePoints = 20; GoalDifference = 3 } }

答案 1 :(得分:6)

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