How to use static extension methods with statically permitted type parameters?

I would like to use statically permitted type parameters with some extension methods that I added to the built-in types, for example float32and int32, so I tried the following:

module Foo =
    type System.Single with
        static member Bar x = x + 1.0f

    let inline bar (x : ^a) =
        (^a : (static member Bar : ^a -> ^a) x)

open Foo
[<EntryPoint>]
let main argv =
    System.Console.WriteLine (bar 1.0f) (* Compilation fails here *)
    0

The compiler complains that The type 'float32' doesn't support the operator 'Bar'. What am I doing wrong?

+4
source share
1 answer

Static resolution options will not be resolved with respect to extension methods, so this particular approach is not possible.

, , , -.

, , , , , , :

type Ext = Ext
    with
        static member Bar (ext : Ext, flt : float) = 1.0 + flt
        static member Bar (ext : Ext, flt : float32) = 1.0f + flt

, , :

let inline bar (x : ^a) =
    ((^b or ^a) : (static member Bar : ^b * ^a -> ^a) (Ext, x))

:

bar 7.0f
val it : float32 = 8.0f

bar 5.0
val it : float = 6.0
+5

Source: https://habr.com/ru/post/1683077/


All Articles