Suppose I wanted to create a Record type that represents acceptable min/max bounds:
type Bounds = { Min: float; Max: float }
Is there a way to enforce that Min < Max? It is easy to write a validateBounds function, I was just wondering if there was a better way to do this.
Edit: I realized that for this specific example I could probably get away with exposing two properties and re-order the arguments, so let's say we were trying to do
type Person = { Name: string }
and Name needs to have at least one character.
Here's another solution based on protection levels:
A dodgy solution for the string example - use a DU
This will force the string to have at least one charcter. Then you can just use
cleverstring
instead ofstring
in your record, although you probably want to write some wrapper functions to make it look like a string.I think your best bet is a static member:
and use it like
However, as you point out, the big down-side of this approach is that there is nothing preventing the construction of an "invalid" record directly. If this is a major concern, consider using a class type for guaranteeing your invariants:
together with an active pattern for convenience similar to what you get with records (specifically with regard to pattern matching):
all together: