f# - 如何在F#中为各种角色定义int、float等类型的同义词?

标签 f#

我想在各种角色中使用像“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/

相关文章:

f# - 将 seq 尾部递归复制到 F# 中的列表

f# 类型成员中静态解析的类型

f# - 将大量函数组合在一起时堆栈溢出

f# - 从静态 ProvidedMethod 返回 ProvidedType

struct - 改变 F# [<Struct>] 记录

f# - System.Collections.Generic 列表和 F#

multithreading - F# MailboxProcessor 限制并行度

multithreading - F# 异步任务取消,无需 token

f# - F#中|>的名称是什么,它有什么作用?

generics - F# 泛型类型重载运算符