How are the following 2 pieces of code equivalent? (how does case work)
list.zipWithIndex.flatMap{
rowAndIndex =>
rowAndIndex._1.zipWithIndex
}
and
list.zipWithIndex.flatMap {
case (rowAndIndex, r) =>
rowAndIndex.zipWithIndex
}
You are probably confused by wrong names in second sample. I changed it to:
list.zipWithIndex.flatMap {
case (row, index) =>
row.zipWithIndex
}
This is short version of:
list.zipWithIndex.flatMap { rowAndIndex =>
rowAndIndex match {
case (row, index) => row.zipWithIndex
}
}
I preferred the first one, since every element here is case (rowAndIndex, r), check it every time seems unnecessary.
And, it seems that you actually don't want the first 'index', why not just use:
list.map(s => s.zipWithIndex).flatten
By the way, I just put following code to http://scalass.com/tryout
val list = List("Abby", "Jim", "Tony")
val a = list.zipWithIndex.flatMap({a =>
a._1.zipWithIndex})
println(a)
val b = list.zipWithIndex.flatMap({case (rowAndIndex, r) =>
rowAndIndex.zipWithIndex})
println(b)
val d = list.map(s => s.zipWithIndex).flatten
println(d)
The output is all like
List((A,0), (b,1), (b,2), (y,3), (J,0), (i,1), (m,2), (T,0), (o,1), (n,2), (y,3))
This is what you want, right?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.