Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the element index when mapping an array in Scala?

Let's consider a simple mapping example:

   val a = Array("One", "Two", "Three")   val b = a.map(s => myFn(s)) 

What I need is to use not myFn(s: String): String here, but myFn(s: String, n: Int): String, where n would be the index of s in a. In this particular case myFn would expect the second argument to be 0 for s == "One", 1 for s == "Two" and 2 for s == "Three". How can I achieve this?

like image 363
Ivan Avatar asked Feb 04 '12 01:02

Ivan


People also ask

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

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.

How do you find the index of an element in an array in CPP?

Using std::find_if algorithm For instance, find the index of the first 2-digit number in the array. The recommended approach is to use the std::find_if algorithm, which accepts a predicate to handle such cases. That's all about finding the index of an element in an array in C++.

Does MAP have index?

The index is used inside map() method to state the position of each element in an array, but it doesn't change the original array. Syntax: array.


1 Answers

Depends whether you want convenience or speed.

Slow:

a.zipWithIndex.map{ case (s,i) => myFn(s,i) } 

Faster:

for (i <- a.indices) yield myFn(a(i),i)  { var i = -1; a.map{ s => i += 1; myFn(s,i) } } 

Possibly fastest:

Array.tabulate(a.length){ i => myFn(a(i),i) } 

If not, this surely is:

val b = new Array[Whatever](a.length) var i = 0 while (i < a.length) {   b(i) = myFn(a(i),i)   i += 1 } 

(In Scala 2.10.1 with Java 1.6u37, if "possibly fastest" is declared to take 1x time for a trivial string operation (truncation of a long string to a few characters), then "slow" takes 2x longer, "faster" each take 1.3x longer, and "surely" takes only 0.5x the time.)

like image 128
Rex Kerr Avatar answered Sep 24 '22 21:09

Rex Kerr