2013-07-24 132 views
2

是否有一種快速的scala慣用法,可以使用索引檢索多個可遍歷的元素。具有多個索引的索引

我在尋找類似

val L=1 to 4 toList 
L(List(1,2)) //doesn't work 

我一直在使用map,到目前爲止,但不知道是否有更多的「斯卡拉」的方式提前

List(1,2) map {L(_)} 

感謝

回答

1

你可以用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) 
+1

我會寫:P – gzm0

9

由於ListFunction你可以寫只是

List(1,2) map L 

儘管如此,如果你要通過索引查找東西,你應該使用IndexedSeqVector代替List

3

您可以添加一個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) 
+0

由於'Vector'實現了'IndexedSeq'特性,我改變了類以豐富特性本身。 – fynn