Partition a collection into “k” close-to-equal pieces (Scala, but language agnostic)

前端 未结 6 2084
南方客
南方客 2021-02-12 15:44

Defined before this block of code:

  • dataset can be a Vector or List
  • numberOfSlices is an Int
6条回答
  •  闹比i
    闹比i (楼主)
    2021-02-12 16:09

    As Kaito mentions grouped is exactly what you are looking for. But if you just want to know how to implement such a method, there are many ways ;-). You could for example do it like this:

    def grouped[A](xs: List[A], size: Int) = {
      def grouped[A](xs: List[A], size: Int, result: List[List[A]]): List[List[A]] = {
        if(xs.isEmpty) {
          result
        } else {
          val (slice, rest) = xs.splitAt(size)
          grouped(rest, size, result :+ slice)
        }
      }
      grouped(xs, size, Nil)
    }
    

提交回复
热议问题