Search code examples
scalafor-loopscala-collectionsfor-comprehension

Iterate through scala Vector and pair a certain object with the next one


Assuming that I have a collection (Vector[Int]),1,2,5,4,3,5,5,5,6,7,7 and want to get another collection (Vector[Vector[Int]]) pairing every number 5 with the next number (1),(2),(5,4),(3),(5,5),(5,6),(7),(7) what are my options apart from this:

var input= Vector.[Int]
var output = Vector.empty[Vector[Int]]
var skip = false

  for(i <- input.indices){
    if (input(i) == 5 && skip == false){
      output = output :+ input(i) :+ input(i + 1)
      skip = true;
    }else if(input(i - 1) != 5){
      output = output :+ input(i)
    }else{
      skip = false;
    }
  }

which works but is not very scala-like. Would it be possible to achieve the same result with a for comprehension? for(x <- c; if cond) yield {...}


Solution

  • You can use foldLeft

    val output = input.foldLeft (Vector.empty[Vector[Int]]) { (result, next) =>
        if(!result.isEmpty && result.last == Vector(5)) {
            result.dropRight(1) :+ Vector(5, next)
        } else {
          result :+ Vector(next)
        }
    }