Functions with generic parameter types

前端 未结 5 1574
傲寒
傲寒 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:31

    Yes, this can be done. Take a look at this hubFS thread.

    In this case, the solution would be:

    let inline retype (x:'a) : 'b = (# "" x : 'b #)
    let inline sqrt_int (n:'a) = retype (sqrt (float n)) : 'a
    

    Caveat: no compile-time type checking. I.e. sqrt_int "blabla" compiles fine but you'll get a FormatException at runtime.

提交回复
热议问题