Combining discriminatory associations with record types

I am trying to deal with discriminatory unions and record types; in particular, how to combine them for maximum readability. Here is an example: let's say that a sports team can have either points (both points in the league and the difference in goals), or it can be suspended from the league, in which case it does not have points or difference in goals. Here is how I tried to express it:

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 } 

The problem occurs at the end of the last line, where I say "State = points". I get β€œIt is expected that the expression should be of type TeamState, but there is a type ofβ€œ Points ”here. How can I get around this?

+6
source share
2 answers
 let portsmouth = { Name = "Portsmouth"; State = CurrentPoints points } 
+5
source

To add some details to answer the pad, the reason your initial version did not work is because the value type assigned by State should be a discriminative join value of type TeamState . In your expression:

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

... type points is points . In the version published by the pad, the CurrentPoints points expression CurrentPoints points constructor to create a distinguishable join value representing CurrentPoints . Another option that gives you a union: Suspended , which can be used as follows:

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

If you did not use the constructor name, it is not clear how you built the suspended command!

Finally, you can also write everything on one line, but it is not so readable:

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

Source: https://habr.com/ru/post/913053/


All Articles