Scala内部DSL限制

时间:2015-01-02 08:43:22

标签: scala dsl

case class Box(x: Int, y: Int, z: Int)    
case class Boxes(s: Set[Box])

val m = Boxes(Set(Box(1,2,3), Box(2,3,4), Box(3,4,5)))

下面的DSL允许指定BoxBoxes上收集的字段的约束,例如,

m x (>,1)
res: Boxes = Boxes(Set(Box(2,3,4), Box(3,4,5)))

m y (>=,4)
res: Boxes = Boxes(Set(Box(3,4,5)))

DSL,

abstract class Ord
case object >= extends Ord
case object > extends Ord

case class Constraints(xs: Boxes) {
  def x(o: Ord, i: Int) = o match {
    case >= => Boxes( xs.s.filter(_.x >= i) )
    case >  => Boxes( xs.s.filter(_.x >  i) )
  }
  def y(o: Ord, j: Int) = o match {
    case >= => Boxes( xs.s.filter(_.y >= j) )
    case >  => Boxes( xs.s.filter(_.y >  j) )
  }
}

implicit def b2c(m: Boxes) = Constraints(m)

查询,

  • Constraints可以针对其他Ord和/或Box维度进行更大的扩展吗?
  • 可以实现以下语法

    m x> 1

0 个答案:

没有答案