Skip to content

2.09 Access the row above (sliding)

Boris Shilov edited this page Jun 21, 2019 · 3 revisions

Access the row 'above'

Using the standard scala sliding method you can access the preceding n rows.

Seq(1,2,4,8).sliding(2).toList
res8: List[Seq[Int]] = List(List(1, 2), List(2, 4), List(4, 8))

Calculate the difference:

Seq(1,2,4,8).sliding(2).toList.map(x=>x(1)-x(0))
res9: List[Int] = List(1, 2, 4)

Use sliding with a CollSeq:

CollSeq(('Jan,1),
        ('Feb,2),
        ('Mar,4),
        ('Apr,8))._2.sliding(2).map(x=>x(1)-x(0)).toList

res12: List[Int] = List(1, 2, 4)

Create a new CollSeq with the difference in the last column:

CollSeq(('Jan,1),
        ('Feb,2),
        ('Mar,4),
        ('Apr,8)) flatZip (0::res12)

res13: com.github.marklister.collections.immutable.CollSeq3[Symbol,Int,Int] =
CollSeq(('Jan,1,0),
        ('Feb,2,1),
        ('Mar,4,2),
        ('Apr,8,4))