Doa*_*oaz 9 generics f# functional-programming type-variables
我试图为(!)运算符定义更一般的情况,如下所示,
let inline (!) (cell : ^a) =
(^a : (member Value : ^b) cell)
Run Code Online (Sandbox Code Playgroud)
因此它不仅适用于ref类型,而且适用于具有Value成员的任何类型.
> !(ref 10) ;;
val it : int = 10
> !(lazy 5) ;;
val it : int = 5
Run Code Online (Sandbox Code Playgroud)
但是当我尝试将它应用于具有类型变量的类型时会出现问题,
> let getValue (c : 'a ref) = !c ;;
let getValue (c : 'a ref) = !c ;;
------------------^^
C:\Users\User\AppData\Local\Temp\stdin(6,19): warning FS0064: This construct causes code to be less generic than indicated by the type annotations. The type variable 'a has been constrained to be type 'obj'.
val getValue : c:obj ref -> obj
Run Code Online (Sandbox Code Playgroud)
如果我扩展内联函数它工作正常.
> let getValue (c : 'a ref) = c.Value ;;
val getValue : c:'a ref -> 'a
Run Code Online (Sandbox Code Playgroud)
谁知道为什么会这样?谢谢.
由于您的getValue函数不是内联函数,因此约束将不起作用.
问题是.NET类型系统无法存储F#可以使用的约束类型inline.
因此,如果您具有以这种方式使用内联函数的非内联函数,则会出现错误.