Do macros make naturally chained comparisons possible in Scala?

混江龙づ霸主 提交于 2019-12-24 00:26:00

问题


Scala does not provide chained comparisons as Python does:

// Python:
0 < x <= 3
// Scala:
0 < x && x <= 3

Will Scala 2.10 with the new macro feature enable the programmer write a library that adds this feature? Or is this beyond the scope of Scala's macros?

Macros seem to be the right choice for the implementation of such syntactic sugar as they do not complicate the parser/compiler.


回答1:


You don't need macros for it:

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)

Usage:

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



回答2:


I don't think Scala macros will help here... (and please correct me if I'am wrong, Eugene will certainly check this)

Macros can only be applied on a type-checked AST (and produce also a type-checked AST). Here the problem is that the expression:

0 < x <= 3

Will be evaluate to: (see another post)

((0 < x) <= 3) // type error

and there no such function <=(i: Int) in Boolean.

I don't see a way to make this expression compiling, thus macros are helpless.

Of course you could use a custom class to achieve your goal, but without macros (I could give you an example if needed), a possible syntax could be 0 less x lesseq 3 or x between (0, 3)



来源:https://stackoverflow.com/questions/13450324/do-macros-make-naturally-chained-comparisons-possible-in-scala

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!