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

Kit*_*Kit 7 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 }
Run Code Online (Sandbox Code Playgroud)

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

Tom*_*cek 16

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

let portsmouth = { Name = "Portsmouth"; State = points }
Run Code Online (Sandbox Code Playgroud)

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

let portsmouth = { Name = "Portsmouth"; State = CurrentPoints points }
let portsmouth = { Name = "Portsmouth"; State = Suspended }
Run Code Online (Sandbox Code Playgroud)

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

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

let portsmouth = 
  { Name = "Portsmouth"
    State = CurrentPoints { LeaguePoints = 20; GoalDifference = 3 } }
Run Code Online (Sandbox Code Playgroud)


pad*_*pad 6

let portsmouth = { Name = "Portsmouth"; State = CurrentPoints points }
Run Code Online (Sandbox Code Playgroud)