在Scala中创建中缀操作符



我正在尝试将我的一些Haskell代码翻译成Scala,我在创建中落运算符时遇到了困难。

在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'

现在如果我有两个布尔值p和q其中p == True q == False p <=> q将返回False

我的问题是如何把它翻译成Scala。我看了一下Odersky的Scala编程书中定义的Rational类我试着效仿。这是我所得到的:

class Iff (b : Boolean){
  def <=> (that : Boolean) : Boolean = {
    this.b == that
  }
}
val a = new Iff(true)
println(a.<=>(false))  // returns false as expected

我可能没有在习惯的Scala中做过这个,所以我正在寻求这方面的帮助。

我的问题是:

  1. 我在Scala中实现了这个习惯用法吗?如果没有,在Scala中最好的方法是什么?
  2. 我必须创建这个类来定义这个操作符吗?意思是,我可以像在上面的Haskell代码中那样在Scala中定义一个独立的方法吗?
  3. 如何在Scala中指定操作符的固定级别?即,它的优先级。

您可以定义implicit class

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

现在你可以不使用new调用它:

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

最新更新