Functions with generic parameter types

前端 未结 5 1569
傲寒
傲寒 2020-11-27 02:38

I am trying to figure out how to define a function that works on multiple types of parameters (e.g. int and int64). As I understand it, function overloading is not possible

5条回答
  •  北海茫月
    2020-11-27 03:39

    This works:

    type T = T with
        static member ($) (T, n:int  ) = int   (sqrt (float n))
        static member ($) (T, n:int64) = int64 (sqrt (float n))
    
    let inline sqrt_int (x:'t) :'t = T $ x
    

    It uses static constraints and overloading, which makes a compile-time lookup on the type of the argument.

    The static constraints are automatically generated in presence of an operator (operator $ in this case) but it can always be written by hand:

    type T = T with
        static member Sqr (T, n:int  ) = int   (sqrt (float n))
        static member Sqr (T, n:int64) = int64 (sqrt (float n))
    
    let inline sqrt_int (x:'N) :'N = ((^T or ^N) : (static member Sqr: ^T * ^N -> _) T, x)
    

    More about this here.

提交回复
热议问题