简体   繁体   English

在Scala中创建中缀运算符

[英]Creating infix operators in Scala

I am trying to translate some of my Haskell code into Scala and I am having difficulty with creating infix operators. 我正在尝试将我的一些Haskell代码转换为Scala,并且我在创建中缀运算符时遇到了困难。

In Haskell say I have this infix operator defined as: 在Haskell中我说这个中缀运算符定义为:

infix 1 <=>                          // this specifies the operator precedence
(<=>) :: Bool -> Bool -> Bool        // this is the type signature of this operator (it says, it takes two Boolean values and returns a Boolean value)
x <=> y = x == y                     // this is the definition of the operator, it is mimicking the behaviour of the logical implication 'if-and-only-if'

So now if I have two booleans, p and q where p == True and q == False, p <=> q will return False. 所以现在如果我有两个布尔值,p和q,其中p == True和q == False,p <=> q将返回False。

My question is how do I go about translating this into Scala. 我的问题是如何将其转换为Scala。 I had a look at the Rational class defined in Odersky's Programming in Scala book and tried to follow the example. 我看了一下在Odersky的Scala编程书中定义的Rational类,并尝试按照这个例子。 This is as far as I got: 这是我得到的:

class Iff (b : Boolean){
  def <=> (that : Boolean) : Boolean = {
    this.b == that
  }
}

val a = new Iff(true)
println(a.<=>(false))  // returns false as expected

I've probably not done this in idiomatic Scala so I am looking for help in that department. 我可能没有在惯用的Scala中这样做,所以我在那个部门寻求帮助。

My questions are: 我的问题是:

  1. Have I implemented this idiomatically in Scala? 我是否在Scala中以惯用方式实现了此功能? If not, what is that best way to this in Scala? 如果没有,Scala最好的方法是什么?
  2. Did I have to create that class in order to define this operator? 我是否必须创建该类才能定义此运算符? Meaning, can I define a standalone method in Scala like I have in the Haskell code above? 意思是,我可以像上面的Haskell代码中那样在Scala中定义一个独立的方法吗?
  3. How to specify the fixity level of the operator in Scala? 如何在Scala中指定运算符的固定级别? That is, it's precedence level. 也就是说,它是优先级。

You can define implicit class 您可以定义implicit class

implicit class Iff(val b: Boolean) extends AnyVal {
  def <=>(that: Boolean) = this.b == that
}

and now you can call it without using new : 现在你可以不使用new方式调用它:

true <=> false // false
false <=> true // false
true <=> true  // true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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