Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find Indexes *Where*

Tags:

scala

There's a indexWhere function in Vector that finds the index of a match.

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

I wrote this function to find all indexes where such a match occurs.

  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)
  }

However, is there already a built-in function of a collection?

like image 630
Kevin Meredith Avatar asked Oct 29 '13 17:10

Kevin Meredith


People also ask

How do you find the index of an element?

indexOf() The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

What is Find index in JavaScript?

findIndex() The findIndex() method returns the index of the first element in an array that satisfies the provided testing function. If no elements satisfy the testing function, -1 is returned.

How do you find the index of an array in Python?

The index() method returns the index of the given element in the list. If the element is not found, a ValueError exception is raised.

How do you find the index of all elements in an array?

To find the position of an element in an array, you use the indexOf() method. This method returns the index of the first occurrence the element that you want to find, or -1 if the element is not found. The following illustrates the syntax of the indexOf() method.


1 Answers

zipWithIndex, filter, and map are built-ins that can be combined to get all the indices of some predicate.

Get the indices of the even values in the list.

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)

You can also use collect as @0__ notes.

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)
like image 79
Brian Avatar answered Sep 20 '22 10:09

Brian