Friday, May 10, 2013

Scala Lists Zip and Unzip

Zipping is the process of taking two lists and merge them into a single list of tuples, where the first item in each list comprises the first tuple, the second item in each list comprises the second tuple, etc. It's best to think of this operation like a zipper on a jacket where the first teeth on each side of the zipper become merged, the second teeth on each side of the zipper become merged, etc.

Here's an example of two lists that are zipped.

val digits = List(1, 2, 3)
val chars = List("a", "b", "c")
val result = digits zip chars    // result : List((1,"a"), (2,"b"), (3,"c"))


The opposite of the zip method is unzip. Here's the result of unzipping the result from above.

result unzip    // (List(1, 2, 3),List("a", "b", "c"))


No comments:

Post a Comment