[英]f# define generic function for multiple types and overloaded operators
I'm trying to define an inline function that can perform arithmetic operations on multiple types - including on user defined types - in a generic way.我正在尝试定义一个内联 function 可以以通用方式对多种类型(包括用户定义的类型)执行算术运算。 However it seems like the inline function seems to infer it's type prematurely.
然而,似乎内联 function 似乎过早地推断出它的类型。
My custom type is the following:我的自定义类型如下:
type ^T Foo (x: ^T) =
static member inline (*) (x: ^T, y: Foo< ^T>) = Foo x
and here is how I want to use it:这就是我想使用它的方式:
let foo = Foo 1
let F () = 1 * foo // works
let inline G x = 1 * x // G inferred as int -> int
let z1 = G 1 // works
let z2 = G foo // error: expected int not Foo
What is the best way to write generic functions like G while keeping it simple?在保持简单的同时编写像 G 这样的通用函数的最佳方法是什么?
The problem is that F# type inference uses weak resolution here:问题是 F# 类型推断在这里使用了弱分辨率:
let inline G x = 1 * x // G inferred as int -> int
That is, in presence of a binary operator it uses the evidence that one operator is a known type to match the other one with the same type.也就是说,在存在二元运算符的情况下,它使用一个运算符是已知类型的证据来匹配具有相同类型的另一个运算符。
This behavior might change in future versions, in presence of the inline keyword.在存在 inline 关键字的未来版本中,此行为可能会发生变化。
For the moment the standard way write your function is using a generic one:目前,编写 function 的标准方法是使用通用方法:
let inline G x = LanguagePrimitives.GenericOne * x
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.