user51
user51

Reputation: 10143

combining zip and map operations in Scala

I understand map and flatten operations can be combined into flatMap, and filter and map into collect in Scala.

Is there anyway I can combine zip/zipwithIndex with map operation?

Upvotes: 0

Views: 629

Answers (2)

Dennis Hunziker
Dennis Hunziker

Reputation: 1293

If, for some reason, you really wanted a combined version you could write one yourself.

implicit class SeqOps[A](s: Seq[A]) {
    def zipWithIndex2[A1 >: A, B >: Int, That](f: (A, Int) => (A1, B))(implicit bf: CanBuildFrom[Seq[A], (A1, B), That]): That = {
        val b = bf(s)
        var i = 0
        for (x <- s) {
            b += f(x, i)
            i += 1
        }
        b.result()
    }
}

Call it like:

s.zipWithIndex2 {
    case (a, b) => (a + "2", b + 2)
}

I'd really think about this twice though and most likely go with any of the other approaches that have been suggested.

Upvotes: 0

Vladimir Matveev
Vladimir Matveev

Reputation: 127711

There is no single operation in the standard library, as far as I know, but there is an extension method on various tuples, called zipped. This method returns an object which provides methods like map and flatMap, which would perform zipping in step with mapping:

(xs, ys).zipped.map((x, y) => x * y)

This object also is implicitly convertible to Traversable, so you can call more complex methods like mkString or foldLeft.

Upvotes: 2

Related Questions