我想在各种角色中使用像“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?
最佳答案
“明显”的想法,至少我有,是使用单一案例区分联合。
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
您仍然无法在同一角色中混合使用整数和 float 。我想。
关于f# - 如何在F#中为各种角色定义int、float等类型的同义词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36057848/