2013-10-29 51 views
2

Vector中有一個indexWhere函數可找到匹配的索引。查找索引*其中*

def indexWhere(p: (A) ⇒ Boolean, from: Int): Int 
> Finds index of the first element satisfying some predicate after or 
> at some start index. 

http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.Vector

我寫了這個功能找到所有指標,其中這樣的比賽出現。

def getAllIndexesWhere[A,B](as: List[A])(f: (B => Boolean))(g: A => B): Vector[B] = { 
    def go(y: List[A], acc: List[Option[B]]): Vector[B] = as match { 
     case x :: xs => val result = if (f(g(x))) Some(g(x)) else None 
         go(xs, acc :+ result) 
     case Nil => acc.flatten.toVector 
    } 
    go(as, Nil) 
    } 

但是,是否已經有一個集合的內置函數?

回答

9

zipWithIndex,filtermap是可以組合以獲取某些謂詞的所有索引的內置函數。

獲取列表中偶數值的索引。

scala> List(1,2,3,4,5,6,7,8,9,10).zipWithIndex.filter(_._1 % 2 == 0).map(_._2) 
res0: List[Int] = List(1, 3, 5, 7, 9) 

您還可以使用collect作爲@ 0__備註。

scala> List(1,2,3,4,5,6,7,8,9,10).zipWithIndex.collect{ case(a,b) if a % 2 == 0 => b} 
res1: List[Int] = List(1, 3, 5, 7, 9) 
+2

你可以用'collect':'{收集的情況下(ELEM,IDX)如果預解碼(ELEM)=> IDX}' –

+0

很好,布賴恩,謝謝。 你能舉出'collect'的例子@ 0__嗎? –

+2

'(1到10).zipWithIndex.collect {case(elem,idx)if elem%2 == 0 => idx}' –