Overloading + operator in F#

前端 未结 5 2166
半阙折子戏
半阙折子戏 2020-12-18 05:34

So i have this:

open System
open System.Linq
open Microsoft.FSharp.Collections
type Microsoft.FSharp.Collections.List<\'a> with
    static member (+) (         


        
5条回答
  •  余生分开走
    2020-12-18 05:48

    Actually there is a way to 're-wire' existing operators, using static constraints and overloads.

    type ListExtension = ListExtension with
        static member        (?<-) (ListExtension, a , b) = a @ b
        static member inline (?<-) (ListExtension, a , b) = a + b
    
    let inline (+) a b = (?<-) ListExtension a b
    
    // test
    
    let lst = [1;2] + [3;4]
    // val lst : int list = [1; 2; 3; 4]
    
    let sum = 1 + 2 + 3 + 4
    // val sum : int = 10
    

    By using the ternary operator the static constraints will be automatically inferred, another option would be to create a method and write the constraints by hand. The first overload cover the case you want to add (lists), the second covers the existing definition.

    So now in your code you can do:

    for x in (+) a b do
        Console.WriteLine(x)
    

    And that will not break existing (+) for numeric types.

提交回复
热议问题