简体   繁体   中英

Extension operator in F#

Disclaimer: I am very new to F#.

I created a custom type for which I have an addition function. I wanted to extend it to allow addition with the standard + operator (the type is simplified for conciseness):

type MyInt = {N:int}

let sumMyInt n1 n2 = {N=n1.N + n2.N}

type MyInt with
    static member (+)(n1, n2) = sumMyInt n1 n2

let n1 = {N=1}
let n2 = {N=2}

printfn "%O" (n1 + n2)

This works and prints {N=3} . I wanted to lift this operation to lists of MyInt , and if I understand the MSDN docs correctly extending MyInt list requires extension methods. So I write:

open System.Collections.Generic
open System.Runtime.CompilerServices

let sumMyInts = List.map2 sumMyInt

[<Extension>]
type MyIntListExtensions =
    [<Extension>]
    static member inline (+)(ss1, ss2) = sumMyInts ss1 ss2

    [<Extension>]
    static member inline SumMyInts (ss1, ss2) = sumMyInts ss1 ss2


let x = sumMyInts ns1 ns2
let y = ns1.SumMyInts ns2
let z = ns1 + ns2

Now x and y compile and work. z refuses to compile with error:

The type 'MyInt list' does not support the operator '+'

The most surprising part is that this compiles:

let z' = ns1.op_Addition ns2

Am I doing something wrong? How can I define an extension operator?

You cannot do what you want to today in F#, see this RFC .

What you could do is create a global operator that does this:

let inline (@+) (xs: 'a list) (ys: 'a list) =
  List.map2 (+) xs ys


> [1; 2] @+ [3; 4]
- ;;
val it : int list = [4; 6]

Explicitly not shadowing (+) here for obvious reasons:). More about creating operators here: https://learn.microsoft.com/en-us/do.net/fsharp/language-reference/operator-overloading#creating-new-operators

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM