Mat*_*ias 1 validation f# units-of-measurement
我发现F#测量单位的想法非常吸引人.然而,通常情况是某些单位具有他们所居住的特定域.例如,距离是正数,温度大于开尔文零,概率在0和1之间,等等 - 但是我没有看到内置任何内容来表示这个概念,并验证特定值是特定单元的有效度量.计量单位是否支持这样的事情(我不这么认为),如果没有,是否有推荐的方法来实现这种行为?
F#中的度量单位不支持行为.它们是在编译期间用于抛出类型错误的静态机制.您将需要一个对象来封装任何"行为".例如,您可以创建一个type Temperature为绑定检查提供运算符.如果您传递了该对象,则该对象可能会抛出异常-1.0<Kelvin>.
你可以这样做.
[<Measure>]
type Kelvin =
static member ToCelsius kelvin =
(kelvin - 273.15<Kelvin>) * 1.0<Celsius/Kelvin>
and [<Measure>] Celsius =
static member ToKelvin celsius =
(celsius + 273.15<Celsius>) * 1.0<Kelvin/Celsius>
type Temperature(kelvin : float<Kelvin>) =
do
if kelvin < 0.0<Kelvin> then
failwith "Negative Kelvin Temperature"
member this.Celsius with get() = Kelvin.ToCelsius kelvin
member this.Kelvin with get() = kelvin
// could add operators here like (=) or (+)
let good = Temperature(0.0<Kelvin>)
let bad = Temperature(-1.0<Kelvin>)
Run Code Online (Sandbox Code Playgroud)