Grouping a list into lists of n elements in Haskell

前端 未结 4 2155
刺人心
刺人心 2020-12-06 09:33

Is there an operation on lists in library that makes groups of n elements? For example: n=3

groupInto 3 [1,2,3,4,5,6,7,8,9] = [[1,2,3],[4,5,6],[7,8,9]]
         


        
4条回答
  •  甜味超标
    2020-12-06 09:42

    This is ofte called "chunk" and is one of the most frequently mentioned list operations that is not in base. The package split provides such an operation though, copy and pasting the haddock documentation:

     > chunksOf 3 ['a'..'z']
     ["abc","def","ghi","jkl","mno","pqr","stu","vwx","yz"]
    

    Additionally, against my wishes, hoogle only searches a small set of libraries (those provided with GHC or perhaps HP), but you can explicitly add packages to the search using +PKG_NAME - hoogle with Int -> [a] -> [[a]] +split gets what you want. Some people use Hayoo for this reason.

提交回复
热议问题