这是一种在编译时限制它的方法.首先创建函数的通用版本:
let inline twice x = x + x
Run Code Online (Sandbox Code Playgroud)
然后使用重载决策和静态成员约束将其限制为所需的类型:
type T = T with
static member ($) (T, x:int ) = twice x
static member ($) (T, x:int64) = twice x
let inline restrictedTwice x = T $ x
Run Code Online (Sandbox Code Playgroud)
测试:
restrictedTwice 4 //val it : int = 8
restrictedTwice 5L //val it : int64 = 10L
restrictedTwice 5u // doesn't compile
Run Code Online (Sandbox Code Playgroud)