score:77
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.)
score:0
Index can also be accessed via the second element of tuples generated by the zipWithIndex
method:
val a = Array("One", "Two", "Three")
val b = a.zipWithIndex.map(s => myFn(s._1, s._2))
score:5
A general tip: Use .iterator
method liberally, to avoid creation of intermediate collections, and thus speed up your computation. (Only when performance requirements demand it. Or else don't.)
scala> def myFun(s: String, i: Int) = s + i
myFun: (s: String, i: Int)java.lang.String
scala> Array("nami", "zoro", "usopp")
res17: Array[java.lang.String] = Array(nami, zoro, usopp)
scala> res17.iterator.zipWithIndex
res19: java.lang.Object with Iterator[(java.lang.String, Int)]{def idx: Int; def idx_=(x$1: Int): Unit} = non-empty iterator
scala> res19 map { case (k, v) => myFun(k, v) }
res22: Iterator[java.lang.String] = non-empty iterator
scala> res22.toArray
res23: Array[java.lang.String] = Array(nami0, zoro1, usopp2)
Keep in mind that iterators are mutable, and hence once consumed cannot be used again.
An aside: The map
call above involves de-tupling and then function application. This forces use of some local variables. You can avoid that using some higher order sorcery - convert a regular function to the one accepting tuple, and then pass it to map
.
scala> Array("nami", "zoro", "usopp").zipWithIndex.map(Function.tupled(myFun))
res24: Array[java.lang.String] = Array(nami0, zoro1, usopp2)
score:5
What about this? I think it should be fast and it's pretty. But I'm no expert on Scala speed...
a.foldLeft(0) ((i, x) => {myFn(x, i); i + 1;} )
Source: stackoverflow.com
Related Query
- How to get the element index when mapping an array in Scala?
- How to get a scala Map value, when the key is a tuple in which only the first element is known?
- How Scala Array apply method returns the value at the index when the implementation is simply throw new error
- How to get the final element of a hierarchical array in scala and apply aggregate functions on it?
- How to get last element of an array in scala
- How to get the proper return type when using a filter based on type in Scala
- How to do this in Scala way: get the first element from Option[Seq[String]]
- How could I get the first K element in scala Array?
- Scala how to repeat the first element of Array until Array.size reach a certain number
- how to use an array element as a for loop index variable in scala
- How to get index of transformed array in scala
- How do I get the type signature to agree with the scala compiler when extracting a value out of an Option[A]?
- How the get the index of the duplicate pair in the scala list
- How to use different names when mapping JSON array to Scala object using combinators
- How to get the current and next element of List of list of options in scala
- how to get the index of the duplicate pair in the a list using scala
- How to convert a list to list of lists by group the elements when an element repeats in Scala idiomatic way
- how to get all element from array of arrays of spark dataframe column scala
- How to get the mouse "x" and "y" when I click in scala
- How to get the index of the current char while iterating over a string in scala
- How can I get the post parameter value from the HttpErrorHandler part when an error occurs in scala playframework?
- How do I get the Scala version from within Scala itself?
- How the get the classOf for a scala object type
- Finding the index of an element in a list scala
- In Scala, how to get a slice of a list from nth element to the end of the list without knowing the length?
- How to get around the Scala case class limit of 22 fields?
- How to get the current date without time in scala
- How do I get the nth element of a Seq?
- How to get a random element from a Set in Scala
- How to get the option to create a new Scala Worksheet in IntelliJ?
More Query from same tag
- Intellij's "Language level" settings
- Scala Netty How to create a simple client for byte data based protocol?
- Scala calling super from a base class that extends a java class
- Spark - creating schema programmatically with different data types
- What's the effect of `override` in concrete class extending abstract class?
- What is the equivalent expression of this spark code (scala) in pyspark?
- Is there a way to get warnings/errors when a return value of a specific type is unused?
- How to broadcast a cold observable: Replay with back-pressure?
- This keyword with scala and anonymous functions/classes
- akka-http chunked response concatenation
- How to write a Scala parser for paths?
- Does Akka cache actor invocation?
- Kafka: Republish 24 hours of messages at the time they were initially published
- How to get constructor argument names using Scala-Macros
- Basic Play framework routing and web sockets example
- How to know in scala runtime the different join types spark
- Cannot get Scala Worksheet to evaluate inside of an object on Intellij
- How to create variable numbers of nested "map" functions in Scala?
- Scala - Is there any way to convert pattern matching into if / else?
- Play 2 Json format, capture Int or String
- for vs map in functional programming
- Generic function for Scala sequences like `Seq`, `IndexedSeq`, `List`
- Circe asJson not encoding properties from abstract base class
- Covariance and type inference in Scala
- Analyse abstract data
- IntelliJ Idea JDK path
- Find the smallest value in an array excluding 0
- sparkml setParallelism for crossvalidator
- Creating IO bundles using dynamic parameters in chisel using MixedVec
- How do I build multiple jar files using scala sbt