在Scala中创建中缀运算符 [英] Creating infix operators in Scala

查看:136
本文介绍了在Scala中创建中缀运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



在Haskell中,我将这个中缀运算符定义为:我想将一些Haskell代码转换为Scala,并且我在创建中缀运算符时遇到了困难。 :

  infix 1 =< => //这指定运算符优先级
(< =>):: Bool - >布尔 - > Bool //这是这个运算符的类型签名(它说,它需要两个布尔值并返回一个布尔值)
x <=> y = x == y //这是运算符的定义,它模仿了逻辑蕴涵'if-and-only-如果'


所以现在如果我有两个布尔值,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))//如预期那样返回false

可能不会在惯用Scala中做到这一点,所以我正在寻找该部门的帮助。



我的问题是:


  1. 我在Scala中实现了这种惯用吗?如果没有,那么在Scala中最好的方法是什么?

  2. 为了定义这个运算符,我必须创建那个类吗?意思是,我可以在Scala中定义一个独立的方法,就像我在上面的Haskell代码中那样?

  3. 如何在Scala中指定运算符的固定级别?


解决方案

您可以定义 implicit class

 隐式类Iff(val b:Boolean)extends AnyVal {
def< ; =>(that:Boolean)= this.b == that
}

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

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


I am trying to translate some of my Haskell code into Scala and I am having difficulty with creating infix operators.

In Haskell say I have this infix operator defined as:

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.

My question is how do I go about translating this into Scala. I had a look at the Rational class defined in Odersky's Programming in Scala book and tried to follow the example. 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.

My questions are:

  1. Have I implemented this idiomatically in Scala? If not, what is that best way to this in Scala?
  2. Did I have to create that class in order to define this operator? Meaning, can I define a standalone method in Scala like I have in the Haskell code above?
  3. How to specify the fixity level of the operator in Scala? That is, it's precedence level.

解决方案

You can define 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 :

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

这篇关于在Scala中创建中缀运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆