宏是否可以在Scala中进行自然链接的比较? [英] Do macros make naturally chained comparisons possible in Scala?

查看:152
本文介绍了宏是否可以在Scala中进行自然链接的比较?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  // Python:
0< x <= 3
// Scala:
0< x&&将Scala 2.10与新的宏功能使程序员写一个库,添加这个功能?或者,这超出了 Scala的宏的范围?



解决方案

你不需要这样的语法糖,因为它不会使解析器/编译器复杂化。不需要宏:

  class ChainedComparisons [T:Ordering](val res:Boolean,right:T){
def< ^(next:T)= new ChainedComparisons(res& Ordering [T] .lt(right,next),next)
def< = ^新的链接的比较(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] T> = new StartChainedComparisons(left)

用法:


$ b b

  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 1 <^ 2 <= ^ 5 <^ 10:Boolean
res5:Boolean = true


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.

解决方案

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

这篇关于宏是否可以在Scala中进行自然链接的比较?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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