是否可以强制记录尊重某些不变量? [英] Is it possible to enforce that a Record respects some invariants?
本文介绍了是否可以强制记录尊重某些不变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我想创建一个表示可接受的最小/最大界限的 Record 类型:
Suppose I wanted to create a Record type that represents acceptable min/max bounds:
type Bounds = { Min: float; Max: float }
有没有办法强制 Min <最大限度?编写 validateBounds 函数很容易,我只是想知道是否有更好的方法来做到这一点.
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.
我意识到对于这个特定的例子,我可能会暴露两个属性并重新排列参数,所以假设我们正在尝试这样做
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:
module MyModule =
type Bounds = private { _min: float; _max: float } with
// define accessors, a bit overhead
member public this.Min = this._min
member public this.Max = this._max
static member public Make(min, max) =
if min > max then raise (ArgumentException("bad values"))
{_min=min; _max=max}
// The following line compiles fine,
// e.g. within your module you can do "unsafe" initialization
let myBadBounds = {_min=10.0; _max=5.0}
open MyModule
let b1 = Bounds.Make(10.0, 20.0) // compiles fine
let b1Min = b1.Min
let b2 = Bounds.Make(10.0, 5.0) // throws an exception
// The following line does not compile: the union cases of the type 'Bounds'
// are not accessible from this code location
let b3 = {_min=10.0; _max=20.0}
// The following line takes the "bad" value from the module
let b4 = MyModule.myBadBounds
这篇关于是否可以强制记录尊重某些不变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文