scala - Scala 中的链式比较

标签 scala

Python 支持“链式比较”的优雅语法,例如:

0 <= n < 256

意思,

0 <= n and n < 256

知道它在语法上是一种相当灵活的语言,是否可以在 Scala 中模拟此功能?

最佳答案

Daniel的回答很全面,实际上很难添加任何内容。由于他的回答提出了他提到的其中一个选择,我只想补充我的 2 美分,并以另一种方式提出一个非常简短的解决方案。丹尼尔的描述:

You could, theoretically, feed the result of the one of the methods to another method. I can think of two ways of doing that:

  • Having <= return an object that has both the parameter it received and the result of the comparision, and having < use both these values as appropriate.

CmpChain 将用作已与最右边的自由对象进行比较的累加器,以便我们可以将其与下一个进行比较:

class CmpChain[T <% Ordered[T]](val left: Boolean, x: T) {
  def <(y: T) = new CmpChain(left && x < y, y)
  def <=(y: T) = new CmpChain(left && x <= y, y)
  // > and >= are analogous

  def asBoolean = left
}

implicit def ordToCmpChain[T <% Ordered[T]](x: T) = new AnyRef {
  def cmp = new CmpChain(true, x)
}
implicit def rToBoolean[T](cc: CmpChain[T]): Boolean = cc.asBoolean

您可以将其用于任何有序类型,例如 IntDouble:

scala> (1.cmp < 2 < 3 <= 3 < 5).asBoolean                          
res0: Boolean = true

scala> (1.0.cmp < 2).asBoolean
res1: Boolean = true

scala> (2.0.cmp < 2).asBoolean
res2: Boolean = false

隐式转换将产生 Boolean ,它应该是:

scala> val b: Boolean = 1.cmp < 2 < 3 < 3 <= 10  
b: Boolean = false

关于scala - Scala 中的链式比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1164668/

相关文章:

scala - 如何指定 JVM 最大堆大小 "-Xmx"以在 SBT 中运行具有 "run"操作的应用程序?

scala - Java SortedMap 到 Scala TreeMap

scala - 引用透明度

scala - 如何在 Spark-scala 中实现 LEAD 和 LAG

scala - Scala 中的类型提取

scala - 从 Scala 源访问 SBT 设置

ruby - 扩展 Scala 特性的对象。 ruby 等效?

scala - Spark : java. lang.UnsupportedOperationException : No Encoder found for java. time.LocalDate

r - sparklyr hadoop配置

Scala 惰性并行集合(可能吗?)