【发布时间】:2013-12-23 22:08:28
【问题描述】:
我想使用tagged types 来指示集合是否已排序。例如:
type Tagged[U] = { type Tag = U }
type @@[T, U] = T with Tagged[U]
class Tagger[U] {
def apply[T](t : T) : T @@ U = t.asInstanceOf[T @@ U]
}
def tag[U] = new Tagger[U]
trait Sorted
现在我想定义一个需要对集合进行排序的方法:
implicit final class RichIndexedSeq[A, CC <: IndexedSeq[A]](val sq: CC)
extends AnyVal {
/** Nearest percentile (rounded index, no interpolation). */
def percentile(n: Int)(implicit sorted: CC <:< Tagged[Sorted]): A =
sq((sq.size * n - 50) / 100)
}
我更愿意将标签检查保留为隐式证据参数,因为将有其他方法进入RichIndexedSeq,它们没有该约束。
不过,我一定是做错了什么。我希望这会起作用:
val x = Vector.fill(10)((math.random * 100).toInt)
val y = tag[Sorted](x.sorted)
但它没有:
y.percentile(50)
<console>:44: error: value percentile is not a member of
@@[scala.collection.immutable.Vector[Int],Sorted]
y.percentile(50)
^
问题必须源于扩展方法间接,因为这样可行:
implicitly[Vector[Int] @@ Sorted <:< Tagged[Sorted]]
【问题讨论】:
标签: scala collections types