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?

3 answers

  • answered 2018-03-13 21:12 Andrey Tyukin

    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`
    }
    

  • answered 2018-03-13 21:49 jwvh

    Here's one way to supply the head of your sequence to every subsequent element.

    val sq:Seq[Int] = Seq(. . .)
    
    sq.headOption.fold(sq){hd =>
      sq.tail.map(/*map() or fold() with the hd value*/)
    }
    

    Note that this is safe for collections of 1 or zero elements.

  • answered 2018-03-13 22:10 Jordan Cutler

    Can make your own fold which supports previous element. Safe with 1 or zero element collections.

      def foldLeftWithPrevious[A, B](as: Seq[A], accumulator: B)(f: (B, A, A) => B): B = {
        @scala.annotation.tailrec
        def foldLeftInner(list2: Seq[A], previous: A, accumulator: B, f: (B, A, A) => B): B = {
          if (list2.isEmpty) accumulator
          else foldLeftInner(list2.tail, list2.head, f(accumulator, previous, list2.head), f)
        }
    
        if (as.length <= 1) accumulator
        else foldLeftInner(as.tail, as.head, accumulator, f)
      }
    

    Feel free to test it with this snippet.

    val foldLeftTest = Seq(1)
      foldLeftWithPrevious(foldLeftTest, 0)((accum, previous, current) => {
        println("accum = " + accum)
        println("previous = " + previous)
        println("current = " + current)
        println("accum will be... " + accum + " + " + previous + " + " + current)
        println("which is... " + (accum + previous + current))
        accum + previous + current
      })