Overload operator in F#: (/)

后端 未结 4 1141
情书的邮戳
情书的邮戳 2020-12-17 15:08

I would like to overload the (/) operator in F# for strings and preserve the meaning for numbers.

/// Combines to path strings
let (/) path1 path2 = Path.Com         


        
4条回答
  •  误落风尘
    2020-12-17 16:03

    I don't think that there is a straightforward way to do that. Extension members aren't taken into consideration for operator overloading in F#, and there isn't a good way to redefine the operation in a semi-generic way using member constraints.

    It is possible to hack something together that will work, but it's very ugly:

    type DivisionOperations =
      static member Divide(x:int, y:int) = x / y
      static member Divide(path1, path2) = Path.Combine(path1, path2)
    
    let inline div< ^t, ^a, ^b, ^c when (^t or ^a) : (static member Divide : ^a * ^b -> ^c)> a b = ((^t or ^a) : (static member Divide : ^a * ^b -> ^c) (a, b))
    
    let inline (/) x y = div x y
    

提交回复
热议问题