Defining static classes in F#

后端 未结 5 717
故里飘歌
故里飘歌 2021-02-12 03:56

Is it possible to define a static class that contains overloadable members in F#? let module bindings cannot be overloaded, even though they are compiled into stati

5条回答
  •  误落风尘
    2021-02-12 04:08

    There is no facility for defining static types in F#.

    The first alternative is to define a module, but it lacks the capability of overloading functions (which is what you're after). The second alternative is to declare a normal type with static members.

    Regarding the second approach, it is exactly what the accepted answer to your old question described. I refactor the code to explain it easier. First, a dummy single-case discreminated unions is defined:

    type Overloads = Overloads
    

    Second, you exploit the fact that static members can be overloaded:

    type Overloads with
        static member ($) (Overloads, m1: #IMeasurable) = fun (m2: #IMeasurable) -> m1.Measure + m2.Measure 
        static member ($) (Overloads, m1: int) = fun (m2: #IMeasurable) -> m1 + m2.Measure
    

    Third, you propagate constraints of these overloaded methods to let-bounds using inline keyword:

    let inline ( |+| ) m1 m2 = (Overloads $ m1) m2
    

    When you're able to overload let-bounds using this method, you should create a wrapper module to hold these functions and mark your type private.

提交回复
热议问题