簡體   English   中英

F#分機話務員

[英]Extension operator in F#

免責聲明:我對 F# 很陌生。

我創建了一個自定義類型,我有一個加法 function。我想擴展它以允許使用標准+運算符加法(為簡潔起見簡化了該類型):

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)

這有效並打印{N=3} 我想將此操作提升到MyInt列表, 如果我正確理解 MSDN 文檔,擴展MyInt list需要擴展方法。 所以我寫:

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

現在xy編譯並工作。 z拒絕編譯並出現錯誤:

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

最令人驚訝的部分是這個編譯:

let z' = ns1.op_Addition ns2

難道我做錯了什么? 如何定義擴展運算符?

你今天不能在 F# 中做你想做的事,請參閱此 RFC

可以做的是創建一個執行此操作的全局運算符:

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


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

出於顯而易見的原因,這里明確不隱藏(+) :)。 有關在此處創建運算符的更多信息: https://learn.microsoft.com/en-us/do.net/fsharp/language-reference/operator-overloading#creating-new-operators

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM