Author

Alejandro Alcalde

Graduado en Ingeniería Informática en la ETSIIT, Granada. Creador de El Baúl del Programador

More Alejandro Alcalde's posts

When I first started working with scala I’ve found myself unable to do trivial things I have being doing in other languages I already known. That is the most frustrating part of learning a new programming language, in my opinion.

Iterate through multiple collections at once in python

One common thing to do is iterate through two collections at a time. The pythonic way of doing this is simple:

collection1 = (1, 2, 3, 4, 5)
collection2 = ('a', 'b', 'c', 'd', 'e')

for i,j in zip(collection1, collection2):
     print i,j

which result is:

1 a
2 b
3 c
4 d
5 e



Iterate through multiple collections at once in scala

Now, what is the idiomatic way of doing it in scala?. In my case I needed to iterate through the collection and also have the index of the current item being iterated, this can be achieved with the method zipWithIndex, then call zipped along with any collection you want to iterate at the same time:

private val tree: Vector[Node] = {
  val indexedWords = words.zipWithIndex

  (indexedWords, tags, dep).zipped.map {
    (w, t, d) =>
      new Node(w._1, w._2, t, d)
  }
}

In the example above I am zipping together three collections (indexedWords, tags, dep), which correspond with types ((String, Int), String, Int).

Before I knew about the idiomatic way I was iterating trough the collection in a ugly way:

/** Constituent tree of this sentence; includes head words */
private val tree: Vector[Node] = words.map(w => {
   val i = words.indexOf(w)
   new Node(w, i, tags.head, 0)
})

This code is part of my final project in Computer Engineering, it was about creating a Dependency Parser, you can check it on GitHub: NLP_Dependency_Parsing

References

Spot a typo?: Help me fix it by contacting me.

Categories:Tags:

Maybe this posts are also worth reading