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.

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...