我想在各种角色中使用像'int'这样的简单类型,编译器会阻止我无意中混淆不同角色的变量。使用度量单位似乎提供了一种(轻)方法来解决它。
[<Measure>]
type xcoordinate
[<Measure>]
type ycoordinate
type xci = int<xcoordinate>
type yci = int<ycoordinate>
let fnc (x:xci) (y:yci) = ...
// Now 'fnc' can be called only with a proper x-y coordinate pair.
// Is there any way to use the type synonyms to coerce an 'int' to
// int<xcoordinate> instead of writing 2<xcoordinate>, for instance?
答案 0 :(得分:1)
“显而易见”的想法,至少我是使用单一案例的歧视联盟。
type XCoordinate = XCoordinate of int
type YCoordinate = YCoordinate of int
let fnc (x:XCoordinate) (y:YCoordinate) = ()
let x = 1
let y = 1
let xc = XCoordinate(x)
let yc = YCoordinate(y)
let resNoCompile = fnc x y //wont compile
let res = fnc xc yc //works as expected
您仍然无法在同一角色中混合使用整数和浮点数。我想。