Scala 自定义运算符(示例 abs) [英] Scala custom operator (example abs)

查看:73
本文介绍了Scala 自定义运算符(示例 abs)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 Scala 允许重载它的默认运算符(+,-!等).是否可以定义自定义运算符并制作类似 |.| 的东西?运算符,以便 |-3|计算结果为 3.或者定义一个像 ++++ 这样的运算符,以便 a ++++ b 等于 a+3*b?

I know that scala allows overloading for it's default operators (+, - ! etc.) . Is it possible to define custom operators and make something like the |.| operator so that | -3| that evaluates to 3. Or defining an operator like ++++ so that a ++++ b equals a+3*b?

推荐答案

你应该看看 scala 运算符文档.

您可以轻松地创建 ++++ 运算符,但不能轻松创建 |.|操作员.

You can easily make the ++++ operator but not the |.| operator.

Scala 中的运算符只是具有非字母数字名称的函数.由于 scala 也支持将 a.f(b) 调用为 f b,因此您可以实现第一个行为.例如:

Operators in scala are just functions with non alphanumeric name. Since scala also support call a.f(b) as a f b then you can achieve the first behavior. For example:

case class A(v: Int) {
  def ++++(b: A): A = A(v + 3 * b.v)
}

val a = A(1)
val b = A(2)
a ++++ b
>> A(7)
a.++++(b) // just another way of doing the exact same call

如果你想把它加到整数上,你只需创建一个隐式类来添加它.

If you want to add this to integer you would simply create an implicit class to add it.

另一种选择是为运算符添加前缀,例如考虑使用 -a 来获得否定.没有应用 - 的第一个元素",而是 - 应用于 a(参见 这个答案).

Another option is to prefix the operator for example consider doing -a to get the negative. There is no "first element" to apply the - to, instead - is applied to a (see this answer).

例如:

case class A(v: Int) {
  def unary_!(): Int = -v
}
val a = A(3)
!a
>> -3

做|.|有两个问题:首先,运算符有两个部分,即它是拆分的.二是使用|

Doing |.| has two issues: First there are two parts to the operator, i.e. it is split. The second is the use of |

为了执行两部分操作符(比如 !.!),您可能想要生成一些私有类型并从其中一个返回它!然后将其用作另一个的输入以返回输出类型.

In order to do a two part operator (say !.!) you would probably want to generate some private type and return it from one ! and then use it as the input for the other to return the output type.

第二个问题是使用|这是一个非法字符.查看此答案,获取合法字符列表

The second issue is the use of | which is an illegal character. Look at this answer for a list of legal characters

这篇关于Scala 自定义运算符(示例 abs)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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