Overloading + operator in F#

前端 未结 5 2155
半阙折子戏
半阙折子戏 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:44

    As pointed out by the other answers, you cannot add implementation of + to an existing type, because extension members are ignored and standalone let binding hides the default (overloaded) implementation.

    If you wanted to use + (which is not really needed because F# library contains operator @), you would have to write wrapper for F# list that supports the operator directly:

    open System.Collections
    open System.Collections.Generic
    
    /// Wrapper for F# list that exposes '+' operator and 
    /// implements 'IEnumerable<_>' in order to work with 'for'
    type PlusList<'T>(list : list<'T>) =
      member x.List = list
      static member (+) (first : PlusList<'a>, second : PlusList<'a>) =
        first.List @ second.List
      interface IEnumerable with
        member x.GetEnumerator() = (list :> IEnumerable).GetEnumerator()
      interface IEnumerable<'T> with
        member x.GetEnumerator() = (list :> IEnumerable<_>).GetEnumerator()
    
    // Simple function to wrap list
    let pl l = PlusList<_>(l)
    
    let a = pl [1; 2; 3; 4; 54; 9]
    let b = pl [3; 5; 6; 4; 54]
    
    for x in a + b do
      System.Console.WriteLine(x)
    

提交回复
热议问题