gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 22:29:34 25 4
gpt4 key购买 nike

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

最佳答案

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

let inline twice x = x + x

然后通过使用重载解析和静态成员约束将其限制为所需的类型:
type T = T with
static member ($) (T, x:int ) = twice x
static member ($) (T, x:int64) = twice x

let inline restrictedTwice x = T $ x

测试:
restrictedTwice 4  //val it : int = 8

restrictedTwice 5L //val it : int64 = 10L

restrictedTwice 5u // doesn't compile

关于f# - 如何创建只接受 int32 或 int64 的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35309588/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com