gpt4 book ai didi

使用类型约束的 F# 模式匹配

转载 作者:行者123 更新时间:2023-12-01 06:44:45 24 4
gpt4 key购买 nike

是否可以使用成员约束执行 F# 类型测试模式?
如:

let f x = 
match x with
| :? (^T when ^T : (static member IsInfinity : ^T -> bool)) as z -> Some z
| _ -> None

或者
let g x =
match x with
| (z : ^T when ^T : (static member IsInfinity : ^T -> bool)) -> Some z
| _ -> None

无论哪个工作。

最佳答案

您不能这样做,正如 Petr 所说,静态解析的类型参数在编译时解析。它们实际上是 F# 编译器的一项功能,而不是 .NET 功能,因此为什么此类信息在运行时不可用。

如果你想在运行时检查这个,你可以使用反射。

let hasIsInfinity (x : 'a) =
typeof<'a>.GetMethod("IsInfinity", [|typeof<'a>|])
|> Option.ofObj
|> Option.exists (fun mi -> mi.ReturnType = typeof<bool> && mi.IsStatic)

这将检查名为 IsInfinity 的静态方法。类型为: 'a -> bool

关于使用类型约束的 F# 模式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36750513/

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