How can I use map and receive an index as well in Scala?

前端 未结 8 1786
轮回少年
轮回少年 2020-12-12 23:07

Is there any List/Sequence built-in that behaves like map and provides the element\'s index as well?

相关标签:
8条回答
  • 2020-12-13 00:04

    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

    myIterable map (doIndexed(someFunction))
    

    The doIndexed-Function wraps the interior function which receives both an index an the elements of myIterable. This might be familiar to you from JavaScript.

    Here is a way to achieve this purpose. Consider the following utility:

    object TraversableUtil {
        class IndexMemoizingFunction[A, B](f: (Int, A) => 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) => B): A => B = {
            new IndexMemoizingFunction(f)
        }
    }
    

    This is already all you need. You can apply this for instance as follows:

    import TraversableUtil._
    List('a','b','c').map(doIndexed((i, char) => char + i))
    

    which results in the list

    List(97, 99, 101)
    

    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!

    0 讨论(0)
  • 2020-12-13 00:05

    There are two ways of doing this.

    ZipWithIndex: Creates a counter automatically starting with 0.

      // zipWithIndex with a map.
      val days = List("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat")
      days.zipWithIndex.map {
            case (day, count) => println(s"$count is $day")
      }
      // Or use it simply with a for.
      for ((day, count) <- days.zipWithIndex) {
            println(s"$count is $day")
      }
    

    Output of both code will be:

    0 is Sun
    1 is Mon
    2 is Tue
    3 is Wed
    4 is Thu
    5 is Fri
    6 is Sat
    

    Zip: Use zip method with a Stream to create a counter. This gives you a way to control the starting value.

    for ((day, count) <- days.zip(Stream from 1)) {
      println(s"$count is $day")
    }
    

    Result:

    1 is Sun
    2 is Mon
    3 is Tue
    4 is Wed
    5 is Thu
    6 is Fri
    7 is Sat
    
    0 讨论(0)
提交回复
热议问题