[英]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: 我的问题是:
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.