gpt4 book ai didi

f# - 强制执行显式类型参数

转载 作者:行者123 更新时间:2023-12-03 09:51:35 25 4
gpt4 key购买 nike

我有一个通用函数,很容易让编译器推断出错误的类型参数。类型参数只控制返回类型,如果我不小心错过了类型注释,编译器会推断 obj .

如何在不给它显式类型参数的情况下调用我的函数使其成为编译时错误? Unchecked.defaultof函数按我想要的方式工作:

> Unchecked.defaultof;;

Unchecked.defaultof;;
^^^^^^^^^^^^^^^^^^^

stdin(1,1): error FS0685: The generic function 'defaultof' must be given explicit type argument(s)

最佳答案

defaultof函数使用特殊属性。 F# 源代码再次有用。函数的实现在prim-types.fs ,但属性是在接口(interface)文件prim-types.fsi中添加的.合并的声明将是:

[<RequiresExplicitTypeArguments>] 
let inline unsafeDefault<'T> : 'T = (# "ilzero !0" type ('T) : 'T #)

内联 IL (# ... #)仅限于 F# 核心,但声明是任何人都可以使用的。

您可以在 F# specification 的第 16 节(第 217 页)中找到该属性。 :

When applied to an F# function or method, indicates that the function or method must be given explicit type arguments when used. For example, typeof<int>. This attribute should be used only in F# assemblies.

关于f# - 强制执行显式类型参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6042899/

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