如何创建只接受int32或int64的函数

Car*_*ngo 4 f#

如何定义在F#的函数f只接受一个参数x被限制为类型int32int64

Gus*_*Gus 7

这是一种在编译时限制它的方法.首先创建函数的通用版本:

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)