object Test {
import collection.generic.CanBuildFrom
class Unzip[T, CC[X] <: Traversable[X]]
(coll: CC[(T, Int)])
(implicit bf: CanBuildFrom[CC[(T, Int)], T, CC[T]]) {
def unzipWithIndex: CC[T] = bf(coll) ++= (coll.toSeq sortBy (_._2) map (_._1)) result
}
implicit def installUnzip[T, CC[X] <: Traversable[X]]
(coll: CC[(T, Int)])
(implicit bf: CanBuildFrom[CC[(T, Int)], T, CC[T]]) = new Unzip[T, CC](coll)
def main(args: Array[String]): Unit = {
val x1 = util.Random.shuffle("abcdefgh".zipWithIndex)
println("x1 shuffled = " + x1)
println("x1.unzipWithIndex = " + x1.unzipWithIndex)
val x2 = (1 to 10).toSet.zipWithIndex
println("x2 = " + x2)
println("x2.unzipWithIndex = " + x2.unzipWithIndex)
}
}
% scala Test
x1 shuffled = Vector((f,5), (g,6), (c,2), (d,3), (e,4), (a,0), (h,7), (b,1))
x1.unzipWithIndex = Vector(a, b, c, d, e, f, g, h)
x2 = Set((8,8), (2,5), (3,7), (5,0), (9,4), (4,9), (6,3), (10,1), (7,6), (1,2))
x2.unzipWithIndex = Set(5, 10, 1, 6, 9, 2, 7, 3, 8, 4)