【问题标题】:Complete, efficient NumericLiteral module implementation完整、高效的 NumericLiteral 模块实现
【发布时间】:2011-01-19 21:15:24
【问题描述】:

基于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 

如何改进和完成?

【问题讨论】:

    标签: generics f# literals


    【解决方案1】:

    我将直接联系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 等的转换),并且由于FromInt32 的定义依赖于这些成员的存在,因此它将在运行时失败(也就是说,(10G : float) 甚至 (10G : int) 都会编译但在执行时会抛出异常)。理想情况下,未来版本的 F# 可能会使其按原样工作,但从 F# 2.0 开始,我们需要想出一个解决方法。

    如果我们可以使用与 F# 核心库处理此类问题的方式类似的方法,那就太好了,这需要对所有隐含运算符进行特殊封装,但会导致所有内容都以完美的效率内联:

    let inline FromInt32 (i : int) : ^t =
      cvt i
      when ^t : int   = int i
      when ^t : float = float i
      when ^t : byte  = byte i
      ...
    

    但是,F# 编译器通过 "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 函数仅用于确保 FromInt32 只能应用于从 int 显式转换的类型(或编译器模拟的类型)。在FromInt32 中对constrain() 的实际调用应该在编译期间得到优化。

    使用这种方法,(10G : bigint) 将被编译为类似IntConverterDynamicImplTable&lt;bigint&gt;.Result 10 的值,IntConverterDynamicTable&lt;bigint&gt;.Result 将具有与(System.Func&lt;int,bigint&gt;(bigint.op_Implicit)).Invoke 等效的值(但已缓存,因此委托只创建一次)。同理,(10G : int64)会编译成IntConverterDynamicImplTable&lt;int64&gt;.Result 10,而IntConverterDynamicTable&lt;int64&gt;.Result会有一个等价于转换函数(int64 : int -&gt; int64)的值,所以有几个方法调用的开销,但整体性能应该很好。

    编辑

    但是,如果您只是在寻找比 FromInt32FromInt64 的天真实现更有效的东西,需要时间O(n),这里的版本仍然相对简单并且只需要 O(log n) 时间:

    module SymmetricOps =
      let inline (~-) (x:'a) : 'a = -x
      let inline (+) (x:'a) (y:'a) : 'a = x + y
      let inline (-) (x:'a) (y:'a) : 'a = x - y
      let inline (*) (x:'a) (y:'a) : 'a = x * y
      let inline (/) (x:'a) (y:'a) : 'a = x / y
      let inline (%) (x:'a) (y:'a) : 'a = x % y
    
    module NumericLiteralG = 
      open SymmetricOps
      let inline FromOne() = LanguagePrimitives.GenericOne
      let inline FromZero() = LanguagePrimitives.GenericZero
      let rec compute zero one two (/) (%) Two (+) (-) (*) pow2 rest n =
        if n = zero then rest
        else 
          let rest' =
            let nmod2 = n % two
            if nmod2 = zero then rest
            elif nmod2 = one then rest + pow2
            else rest - pow2
          compute zero one two (/) (%) Two (+) (-) (*) (Two * pow2) rest' (n / two)
      let inline FromInt32 i = compute 0  1  2  (/) (%) (FromOne() + FromOne()) (+) (-) (*) (FromOne()) (FromZero()) i
      let inline FromInt64 i = compute 0L 1L 2L (/) (%) (FromOne() + FromOne()) (+) (-) (*) (FromOne()) (FromZero()) i
    

    【讨论】:

    • 哇。感谢您的精彩解释。
    • 暂时没有凡人可能实现这一点,是否有更简单的方法来表示任意通用数字?给出了GenericZeroGenericOne,但是GenericN 呢?这对于通用数值运算是必不可少的......并且使用 GenericOne/Zero 进行计算很尴尬。
    • @Daniel - 好吧,我想这取决于您需要它的效率。在您的问题中使用更直接的FromInt32 方法没有任何问题,只是它会导致更多开销。
    • @kvb - 它没有线性成本吗?计算一百万是否会循环一百万次?如果是这样,我希望有更好的方法来解决它。
    • @Daniel - 是的,你是对的,这慢得让人无法接受。我在答案的末尾添加了一个简单的版本,即 O(log n) 而不是 O(n)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-12
    • 2012-09-05
    • 1970-01-01
    • 2010-11-07
    • 2019-03-02
    • 2013-12-05
    • 1970-01-01
    相关资源
    最近更新 更多