Is there any List/Sequence built-in that behaves like map
and provides the element's index as well?
相关问题
- Unusual use of the new keyword
- Get Runtime Type picked by implicit evidence
- F#: Storing and mapping a list of functions
- What's the point of nonfinal singleton objects
- PlayFramework: how to transform each element of a
相关文章
- Gatling拓展插件开发,check(bodyString.saveAs("key"))怎么实现
- RDF libraries for Scala [closed]
- Why is my Dispatching on Actors scaled down in Akk
- Is there something like the threading macro from C
- How do you run cucumber with Scala 2.11 and sbt 0.
- Learning F#: What books using other programming la
- Creating a list of functions using a loop in R
- GRPC: make high-throughput client in Java/Scala
Or, assuming your collection has constant access time, you could map the list of indexes instead of the actual collection:
Use .map in .zipWithIndex with Map data structure
Results
There is
CountedIterator
in 2.7.x (which you can get from a normal iterator with .counted). I believe it's been deprecated (or simply removed) in 2.8, but it's easy enough to roll your own. You do need to be able to name the iterator:If you require searching the map values as well (like I had to):
I believe you're looking for zipWithIndex?
From: http://www.artima.com/forums/flat.jsp?forum=283&thread=243570
You also have variations like:
or:
The proposed solutions suffer from the fact that they create intermediate collections or introduce variables which are not strictly necessary. For ultimately all you need to do is to keep track of the number of steps of an iteration. This can be done using memoizing. The resulting code might look like
The
doIndexed
-Function wraps the interior function which receives both an index an the elements ofmyIterable
. This might be familiar to you from JavaScript.Here is a way to achieve this purpose. Consider the following utility:
This is already all you need. You can apply this for instance as follows:
which results in the list
This way, you can use the usual Traversable-functions at the expense of wrapping your effective function. The overhead is the creation of the memoizing object and the counter therein. Otherwise this solution is as good (or bad) in terms of memory or performance as using unindexed
map
. Enjoy!