程式扎記: [Scala 文章收集] Scala zip and zipWithIndex examples (with Stream)

標籤

2016年7月26日 星期二

[Scala 文章收集] Scala zip and zipWithIndex examples (with Stream)

Source From Here 
Scala zip and zipWithIndex examples (with Stream) 
I’ve known about using Scala’s zipWithIndex method for quite some time. I used it in for loops to replace counters, and it works like this: 
scala> List("a", "b", "c").zipWithIndex
res0: List[(String, Int)] = List((a,0), (b,1), (c,2))

I learned about using zip with Stream last night while reading Joshua Suereth’s book, Scala In Depth. It works like this: 
scala> val s = Stream.from(1)
s: scala.collection.immutable.Stream[Int] = Stream(1, ?)

scala> s(1)
res8: Int = 2

scala> s
res9: scala.collection.immutable.Stream[Int] = Stream(1, 2, ?)

scala> List("a", "b", "c").zip(Stream.from(1))
res10: List[(String, Int)] = List((a,1), (b,2), (c,3))

Both of these approaches are cool. 

The Scaladoc 
The Scaladoc describes the zip method like this: 
Returns a list formed from this list and another iterable collection by combining
corresponding elements in pairs. If one of the two collections is longer than the
other, its remaining elements are ignored.

It describes the zipWithIndex method like this: 
Zips this list with its indices.

Returns: A new list containing pairs consisting of all elements of this list
paired with their index. Indices start at 0.

For more information, see the documentation for the zip and zipWithIndex methods, which you can find on Scala collection classes, such as List.

沒有留言:

張貼留言

網誌存檔

關於我自己

我的相片
Where there is a will, there is a way!