是否有一种快速的scala惯用法,可以使用索引检索多个可遍历的元素。具有多个索引的索引
我在寻找类似
val L=1 to 4 toList
L(List(1,2)) //doesn't work
我一直在使用map
,到目前为止,但不知道是否有更多的“斯卡拉”的方式提前
List(1,2) map {L(_)}
感谢
是否有一种快速的scala惯用法,可以使用索引检索多个可遍历的元素。具有多个索引的索引
我在寻找类似
val L=1 to 4 toList
L(List(1,2)) //doesn't work
我一直在使用map
,到目前为止,但不知道是否有更多的“斯卡拉”的方式提前
List(1,2) map {L(_)}
感谢
你可以用for
理解,但它不会比你使用的代码map
更清晰。
scala> val indices = List(1,2)
indices: List[Int] = List(1, 2)
scala> for (index <- indices) yield L(index)
res0: List[Int] = List(2, 3)
我觉得最可读将实现自己的功能takeIndices(indices: List[Int])
这需要指标的列表,这些索引返回给定List
的值。例如
L.takeIndices(List(1,2))
List[Int] = List(2,3)
由于List
是Function
你可以写只是
List(1,2) map L
尽管如此,如果你要通过索引查找东西,你应该使用IndexedSeq
像Vector
代替List
。
您可以添加一个implicit class,增加的功能:
implicit class RichIndexedSeq[T](seq: IndexedSeq[T]) {
def apply(i0: Int, i1: Int, is: Int*): Seq[T] = (i0+:i1+:is) map seq
}
然后,您可以使用该序列的apply
方法与一个索引或多个索引:
scala> val data = Vector(1,2,3,4,5)
data: scala.collection.immutable.Vector[Int] = Vector(1, 2, 3, 4, 5)
scala> data(0)
res0: Int = 1
scala> data(0,2,4)
res1: Seq[Int] = ArrayBuffer(1, 3, 5)
由于'Vector'实现了'IndexedSeq'特性,我改变了类以丰富特性本身。 – fynn
我会写:P – gzm0