加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

在Scala中创建中缀运算符

发布时间:2020-12-16 09:17:27 所属栏目:安全 来源:网络整理
导读:我正在尝试将我的一些 Haskell代码翻译成 Scala,而且我在创建中缀操作系统时遇到困难. 在Haskell说我有这个中缀运算符定义为: infix 1 = // this specifies the operator precedence(=) :: Bool - Bool - Bool // this is the type signature of this opera
我正在尝试将我的一些 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.我看过在Scala书中的Odersky编程中定义的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中最好的办法是什么?
>为了定义这个运算符,我必须创建该类吗?意思是,我可以在Scala中定义一个独立的方法,就像我在上面的Haskell代码中一样吗?
>如何在Scala中指定运算符的固定级别?那就是它的优先级.

解决方法

您可以定义隐式类

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

现在你可以调用它而不使用新的:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读