Search code examples
scalafold

Fold with previous element


Given val as: Seq[Int] = ...

A lot of times I need to apply an operation to two consecutive elements, e.g.

By the way I don't like

for (i <- 1 until as.size) {
  // do something with as(i) and as(i - 1)
}

Or by another

as.tail.foldLeft((0, as.head)) { (acc, e) =>
  // do something with acc._2 and e 
  // and try to not forget returning (_, e) 
}

How do I writer better code for this scenario?


Solution

  • You could zip the sequence as with its own tail:

    for ((prev, curr) <- as zip as.tail) {
      // do something with `prev` and `curr`
    }
    

    Or you could use sliding:

    for (window <- as.sliding(2)) {
      val prev = window(0)
      val curr = window(1)
      // do something with `prev` and `curr`
    }