F# 将有区别的联合与记录类型相结合

F# 将有区别的联合与记录类型相结合,f#,F#,我正试图了解受歧视的工会和唱片公司;特别是如何组合它们以获得最大的可读性。这里有一个例子——假设一个运动队可以有积分(联赛积分和目标差),或者可以暂停联赛,在这种情况下,它没有积分或目标差。以下是我试图表达的方式: type Points = { LeaguePoints : int; GoalDifference : int } type TeamState = | CurrentPoints of Points | Suspended type Team = { Nam

我正试图了解受歧视的工会和唱片公司;特别是如何组合它们以获得最大的可读性。这里有一个例子——假设一个运动队可以有积分(联赛积分和目标差),或者可以暂停联赛,在这种情况下,它没有积分或目标差。以下是我试图表达的方式:

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

为了给pad的答案添加一些细节,您的初始版本不起作用的原因是分配给
状态
的值类型应该是
团队状态
类型的有区别的联合值。在你的表达中:

let portsmouth = { Name = "Portsmouth"; State = CurrentPoints points }
let portsmouth = { Name = "Portsmouth"; State = points }
…点的类型为点。在pad发布的版本中,表达式
CurrentPoints
使用
TeamState
的构造函数来创建表示
CurrentPoints
的有区别的联合值。工会给您的另一个选项是
挂起
,可以这样使用:

let portsmouth = { Name = "Portsmouth"; State = CurrentPoints points }
let portsmouth = { Name = "Portsmouth"; State = Suspended }
如果您没有使用构造函数的名称,那么就不清楚如何构建一个暂停的团队

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

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

感谢您的详细介绍,托马斯:-)