在Scala中,宏可以自然地进行链式比较吗?

Bas*_*ian 2 comparison scala syntactic-sugar scala-2.10 scala-macros

Scala不像Python那样提供链式比较:

// Python:
0 < x <= 3
// Scala:
0 < x && x <= 3
Run Code Online (Sandbox Code Playgroud)

具有新宏功能的Scala 2.10能否让程序员编写一个添加此功能的库?或者这超出了Scala宏的范围?

宏似乎是实现这种语法糖的正确选择,因为它们不会使解析器/编译器复杂化.

sen*_*nia 6

你不需要宏:

class ChainedComparisons[T : Ordering](val res: Boolean, right: T) {
  def <^ (next: T) = new ChainedComparisons(res && Ordering[T].lt(right, next), next)
  def <=^ (next: T) = new ChainedComparisons(res && Ordering[T].lteq(right, next), next)
}
implicit def chainedComparisonsToBoolean(c: ChainedComparisons[_]) = c.res

class StartChainedComparisons[T : Ordering](left: T) {
  def <^(right: T) = new ChainedComparisons(Ordering[T].lt(left, right), right)
  def <=^(right: T) = new ChainedComparisons(Ordering[T].lteq(left, right), right)
}
implicit def toStartChainedComparisons[T : Ordering](left: T) = new StartChainedComparisons(left)
Run Code Online (Sandbox Code Playgroud)

用法:

scala> val x = 2
x: Int = 2

scala> 1 <^ x : Boolean
res0: Boolean = true

scala> 1 <^ x <^ 3 : Boolean
res1: Boolean = true

scala> 1 <^ x <^ 2 : Boolean
res2: Boolean = false

scala> 1 <^ x <=^ 2 : Boolean
res3: Boolean = true

scala> if (1 <^ x <^ 3) println("true") else println(false)
true

scala> 1 <=^ 1 <^ 2 <=^ 5 <^ 10 : Boolean
res5: Boolean = true
Run Code Online (Sandbox Code Playgroud)