完整,高效的NumericLiteral模块实现

时间:2011-01-19 21:15:25

标签: generics f# literals

this question的讨论基础上,是否有人可以提供代码或代码链接,显示NumericLiteralX模块的完整实现(例如this one)?我特别感兴趣的是FromInt32 / 64有效实现NumericLiteralX模块,以促进通用数字运算。这可能是从上述问题中得到的低效实施:

module NumericLiteralG = 
    let inline FromZero() = LanguagePrimitives.GenericZero
    let inline FromOne() = LanguagePrimitives.GenericOne
    let inline FromInt32 (n:int) =
        let one : ^a = FromOne()
        let zero : ^a = FromZero()
        let n_incr = if n > 0 then 1 else -1
        let g_incr = if n > 0 then one else (zero - one)
        let rec loop i g = 
            if i = n then g
            else loop (i + n_incr) (g + g_incr)
        loop 0 zero 

如何改进和完成?

1 个答案:

答案 0 :(得分:14)

我只会说FromInt32。在理想的世界中,我们可以将其定义为

let inline FromInt32 i = 
  ((^t or int) : (static member op_Explicit : int -> ^t) i)

将使用静态约束来确保我们可以内联int的显式转换。不幸的是,这有两个问题。第一个是语法无效 - 您不能在成员约束的“static-typars”部分中具有具体类型(如int)。我们可以通过定义辅助函数

来解决这个问题
let inline cvt i = ((^t or ^u) : (static member op_Explicit : ^u -> ^t) i)
let inline FromInt32 (i:int) = cvt i

由于这两个函数都是内联的,所以这并不比第一次尝试的效率低,它只是更有用。

这是我们遇到第二个问题的地方:这将适用于真正的op_Explicit定义(或op_Implicit,由编译器专门处理,以便它被op_Explicit包含在内。因此,(10G : bigint)将被内联,就好像您已经编写了System.Numerics.BigInt.op_Implicit 10一样,这是我们所希望的那样高效。但是,对于许多原始类型,F#也会模拟op_Explicit(例如,对于从intfloatbyte等的转换,以及{{1}的定义依赖于这些成员的存在,它将在运行时失败(即FromInt32甚至(10G : float)将编译,但在执行时将抛出异常)。理想情况下,F#的未来版本可能会使其按原样运行,但从F#2.0开始,我们需要提出一种解决方法。

如果我们可以使用类似的方法来解决F#核心库如何处理这类问题,这将是很好的,这将需要特殊的套管所有隐含的运算符,但会导致所有内容都以完美的效率内联:

(10G : int)

但是,F#编译器使用let inline FromInt32 (i : int) : ^t = cvt i when ^t : int = int i when ^t : float = float i when ^t : byte = byte i ... 消息拒绝此消息(并使用秘密"Static optimization conditionals are only for use within the F# library"标志进行编译只会使事情变得更糟:)。)。

相反,我们需要使用一些额外的间接层来在运行时实现类似的功能。首先,我们将使用泛型类型的静态成员创建类型到转换函数的运行时映射:

--compiling-fslib

这类似于我们在前一次尝试中使用静态优化条件尝试实现的内容,但它延迟到运行时而不是在编译时评估的所有内容。现在我们只需要定义一些值来使用这种类型:

type IntConverterDynamicImplTable<'t>() =
  static let result : int -> 't =
    let ty = typeof< 't> //'
    if   ty.Equals(typeof<sbyte>)      then sbyte      |> box |> unbox
    elif ty.Equals(typeof<int16>)      then int16      |> box |> unbox
    elif ty.Equals(typeof<int32>)      then int        |> box |> unbox
    elif ty.Equals(typeof<int64>)      then int64      |> box |> unbox
    elif ty.Equals(typeof<nativeint>)  then nativeint  |> box |> unbox
    elif ty.Equals(typeof<byte>)       then byte       |> box |> unbox
    elif ty.Equals(typeof<uint16>)     then uint16     |> box |> unbox
    elif ty.Equals(typeof<char>)       then char       |> box |> unbox
    elif ty.Equals(typeof<uint32>)     then uint32     |> box |> unbox
    elif ty.Equals(typeof<uint64>)     then uint64     |> box |> unbox
    elif ty.Equals(typeof<unativeint>) then unativeint |> box |> unbox
    elif ty.Equals(typeof<decimal>)    then decimal    |> box |> unbox
    elif ty.Equals(typeof<float>)      then float      |> box |> unbox
    elif ty.Equals(typeof<float32>)    then float32    |> box |> unbox
    else 
      let m = 
        try ty.GetMethod("op_Implicit", [| typeof<int> |])
        with _ -> ty.GetMethod("op_Explicit", [| typeof<int> |])
      let del =
        System.Delegate.CreateDelegate(typeof<System.Func<int,'t>>, m)
        :?> System.Func<int,'t>
      del.Invoke |> box |> unbox
  static member Result = result

这里,let inline constrain< ^t, ^u when (^t or ^u) : (static member op_Explicit : ^t -> ^u)> () = () let inline FromInt32 i : ^t = constrain<int, ^t>() IntConverterDynamicImplTable.Result i 函数仅用于确保constrain只能应用于从int(或编译器模拟的)显式转换的类型。在FromInt32内对constrain()的实际调用应在编译期间进行优化。

使用这种方法,FromInt32将被编译为类似(10G : bigint)的内容,而IntConverterDynamicImplTable<bigint>.Result 10将具有相当于IntConverterDynamicTable<bigint>.Result的值(但是已缓存,因此委托是只创建一次)。同样,(System.Func<int,bigint>(bigint.op_Implicit)).Invoke将编译为(10G : int64),而IntConverterDynamicImplTable<int64>.Result 10将具有与转换函数IntConverterDynamicTable<int64>.Result等效的值,因此存在一些方法调用的开销,但总体而言表现应该非常好。

修改

但是,如果您只是在寻找比(int64 : int -> int64)FromInt32花费时间 O(n)的天真实现更有效的方法,那么这里的版本是仍然相对简单,只需要 O(log n)时间:

FromInt64