遍历 scala Vector 并将某个对象与下一个对象配对

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

假设我有一个集合 (Vector[Int]),1,2,5,4,3,5,5,5,6,7,7 并且想要得到另一个集合 (Vector[Vector[Int]]) 将每个数字 5 与下一个数字配对 (1),(2),(5,4),(3),(5,5),(5,6),(7),(7) 除了这个我还有什么选择:

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

这有效但不是很像 scala。 是否有可能通过 for 理解获得相同的结果? for(x <- c; if cond) yield {...}

您可以使用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)
    }
}

您也可以使用模式匹配

   def prepareVector(lv: Vector[Int]): Vector[Vector[Int]] = {
     val mv = new ArrayBuffer[Vector[Int]]()

     def go(ll: List[Int]): Unit = ll match {
       case y :: Nil => mv += Vector(y)
       case 5 :: ys => {
         mv += Vector(5, ys.head)
         go(ys.tail)
       }
       case y :: ys => {
         mv += Vector(y)
         go(ys)
       }
       case Nil => None
     }

     go(lv.toList)

     mv.toVector
   }