[英]Extension operator in F#
Disclaimer: I am very new to F#.免责声明:我对 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):我创建了一个自定义类型,我有一个加法 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)
This works and prints {N=3}
.这有效并打印{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.我想将此操作提升到MyInt
列表, 如果我正确理解 MSDN 文档,扩展MyInt list
需要扩展方法。 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.现在x
和y
编译并工作。 z
refuses to compile with error: z
拒绝编译并出现错误:
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 .你今天不能在 F# 中做你想做的事,请参阅此 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有关在此处创建运算符的更多信息: https://learn.microsoft.com/en-us/do.net/fsharp/language-reference/operator-overloading#creating-new-operators
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.