Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>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</p> <pre><code>myIterable map (doIndexed(someFunction)) </code></pre> <p>The <code>doIndexed</code>-Function wraps the interior function which receives both an index an the elements of <code>myIterable</code>. This might be familiar to you from JavaScript.</p> <p>Here is a way to achieve this purpose. Consider the following utility:</p> <pre><code>object TraversableUtil { class IndexMemoizingFunction[A, B](f: (Int, A) =&gt; B) extends Function1[A, B] { private var index = 0 override def apply(a: A): B = { val ret = f(index, a) index += 1 ret } } def doIndexed[A, B](f: (Int, A) =&gt; B): A =&gt; B = { new IndexMemoizingFunction(f) } } </code></pre> <p>This is already all you need. You can apply this for instance as follows:</p> <pre><code>import TraversableUtil._ List('a','b','c').map(doIndexed((i, char) =&gt; char + i)) </code></pre> <p>which results in the list</p> <pre><code>List(97, 99, 101) </code></pre> <p>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 <code>map</code>. Enjoy!</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload