如何声明全局级别的可重载运算符? [英] How to declare global level overload-able operators?

查看:72
本文介绍了如何声明全局级别的可重载运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基于:可以定义

我想定义一些像+这样的运算符,但是让我们调用-|-例如

I want to define some operator like + but let call -|- for example to have

let a = -|- 1
let b = 1 -|- 1
let c = 1 -|- 1 1 1 1

至少有2行适用于+,但是我怎么能这样声明自己的运算符?

At least 2 first lines will work for + but how can I declare own operator like this?

推荐答案

一般来说,我认为没有简单的方法可以做到这一点.您可能会使用混合静态成员约束的inline运算符来覆盖所需的一些案例,但我认为这样做不会很优雅.

I don't think there is a straightforward way to do this in general. You could probably use an inline operator with a mix of static member constraints to cover some of the cases that you want, but I don't think it will be very elegant.

对于某些运算符名称,您可以定义一个单独的 prefix infix 版本,其中涵盖了前两种情况:

For some operator names, you can however define a separate prefix and infix version, which covers the first two cases:

// Prefix version of the operator (when you write e.g. '+. 10')
let (~+.) a = a * 10
// Infix version of the operator (when you write e.g. '1 +. 10')
let (+.) a b = a + b

// Sample use
+. 10
10 +. 20

您仍然将无法编写10 +. 20 30 40,因为那样的话您将需要重载的中缀运算符.

You still won't be able to write 10 +. 20 30 40, because then you'd need an overloaded infix operator.

值得注意的是,您不能对所有操作员名称都执行此操作.这是来自 F#规范中用于中缀运算符的允许的运算符名称的语法定义:

It is worth noting that you cannot do this for all operator names. Here is a syntax definition from the F# specification of the allowed operator names for infix operators:

infix-or-prefix-op:=
+,-,+.,-.,%,&,&&

infix-or-prefix-op :=
      +, -, +., -., %, &, &&

prefix-op:=
infix-or-prefix-op
〜~~ ~~~(以及〜的任何重复项)
!OP(!=除外)

prefix-op :=
      infix-or-prefix-op
      ~ ~~ ~~~ (and any repetitions of ~)
      !OP (except !=)

PS:我一般不喜欢自定义运算符-在某些情况下,它们很不错,但是很难发现它们(您在IntelliSense中看不到它们),除非您使用标准运算符进行自定义运算符数值计算,通常很难理解它们的含义.所以我可能会考虑其他方法...

PS: I'm not generally a big fan of custom operators - in some cases, they are nice, but they are difficult to discover (you do not see them in the IntelliSense) and unless you're using standard ones for numerical computing, it is often difficult to understand what they mean. So I would maybe consider other approaches...

这篇关于如何声明全局级别的可重载运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆