gpt4 book ai didi

scala - Scala 中的链式比较

转载 作者:行者123 更新时间:2023-12-02 01:59:50 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com