Split list into multiple lists with fixed number of elements

前端 未结 5 468
独厮守ぢ
独厮守ぢ 2020-12-02 10:17

How to split a List of elements into lists with at most N items?

ex: Given a list with 7 elements, create groups of 4, leaving the last group possibly with less elem

5条回答
  •  盖世英雄少女心
    2020-12-02 10:54

    I think this is the implementation using splitAt instead of take/drop

    def split [X] (n:Int, xs:List[X]) : List[List[X]] =
        if (xs.size <= n) xs :: Nil
        else   (xs.splitAt(n)._1) :: split(n,xs.splitAt(n)._2)
    

提交回复
热议问题