我正在尝试将一些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实现这个,所以我正在寻求帮助。
我的问题是:
- 我在Scala中是否按照惯例实现了这个?如果没有,那么在Scala中最好的方法是什么?
- 我是否必须创建该类来定义此运算符?也就是说,我能否像上面的Haskell代码中那样定义一个独立的方法?
- 如何在Scala中指定运算符的固定级别?也就是它的优先级。