我正在尝试将我的一些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'
Run Code Online (Sandbox Code Playgroud)
所以现在如果我有两个布尔值,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
Run Code Online (Sandbox Code Playgroud)
我可能没有在惯用的Scala中这样做,所以我在那个部门寻求帮助.
我的问题是:
gor*_*ral 17
你可以定义 implicit class
implicit class Iff(val b: Boolean) extends AnyVal {
def <=>(that: Boolean) = this.b == that
}
Run Code Online (Sandbox Code Playgroud)
现在你可以不用使用它来调用它new:
true <=> false // false
false <=> true // false
true <=> true // true
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2988 次 |
| 最近记录: |