我在寻找有关内联函数静态解析类型参数的信息时,偶然发现了FSharp.Core中各种原始运算符的定义:
let inline (+) (x: ^T) (y: ^U) : ^V =
CheckedAdditionDynamic<(^T),(^U),(^V)> x y
when ^T : int32 and ^U : int32 = (# "add.ovf" x y : int32 #)
when ^T : float and ^U : float = (# "add" x y : float #)
// <snip>
when ^T : ^T = ((^T or ^U): (static member (+) : ^T * ^U -> ^V) (x,y))
正如上面的片段中所看到的,
when
关键字以when expr1 = expr2
的格式用于各种内置类型。我猜这是一种编译器等价于“如果T=int使用opcode add.ovf,否则如果…,否则执行”。然而,在F#文档中我找不到任何关于这种语法的参考/解释。有了一些F#内部知识的人能否解释一下上面那个片段中正在发生什么?
(# ... #)
语法)。 - Ramon Snir