Dmi*_*nov 2 f# generic-programming
有一个泛型函数LanguagePrimitives.DivideByInt可以在int不丢失泛型行为的情况下进行除法,我们可以像这样使用它:
let inline Divideby2 n = LanguagePrimitives.DivideByInt n 2
val inline Divideby2 :
^a -> ^a when ^a : (static member DivideByInt : ^a * int -> ^a)
Run Code Online (Sandbox Code Playgroud)
但是没有被称为MultiplyByInt执行泛型乘法的函数int.有没有什么可以执行泛型乘法?像这样:
let inline MultiplyBy2 n = SomeGenericFunctionsModule.MultiplybyInt n 2;
Run Code Online (Sandbox Code Playgroud)
PS我们总是可以使用一些非标准方法,如:
let inline MultiplyByInt n m = seq { for i in 1..m -> n} |> Seq.sum
Run Code Online (Sandbox Code Playgroud)
但我很有兴趣是否有可能以正确的方式做到这一点.
我担心没有内置功能,但我可以提出两种替代解决方案:
type MulExtension = MulExtension of int with
static member (=>) (x:float , MulExtension y) = x * (float y)
static member (=>) (x:decimal, MulExtension y) = x * (decimal y)
static member (=>) (x:int64 , MulExtension y) = x * (int64 y)
// More overloads
let inline MultiplyByInt x y = x => MulExtension y
Run Code Online (Sandbox Code Playgroud)
但是你必须指定每种类型.我宁愿使用这个功能:
let inline MultiplyByInt x y =
let fromInt (n:int) : ^a when ^a : (static member (*) : ^a * ^a -> ^a) =
System.Convert.ChangeType(n, typeof<'a>) :?> 'a
x * (fromInt y)
Run Code Online (Sandbox Code Playgroud)
我看不出两种方法之间在性能上有任何差异.