Skip to content

Commit

Permalink
[ new ] add Data.List.grouped function (#3089)
Browse files Browse the repository at this point in the history
  • Loading branch information
stefan-hoeck authored Oct 13, 2023
1 parent f7d4b7f commit 7fbbb03
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,8 @@

* Adds updating functions to `SortedMap` and `SortedDMap`.

* Adds `grouped` function to `Data.List` for splitting a list into equal-sized slices.

* Implements `Ord` for `Count` from `Language.Reflection`.

* Implements `MonadState` for `Data.Ref` with a named implementation requiring
Expand Down
18 changes: 18 additions & 0 deletions libs/base/Data/List.idr
Original file line number Diff line number Diff line change
Expand Up @@ -925,6 +925,24 @@ public export
groupAllWith : Ord b => (a -> b) -> List a -> List (List1 a)
groupAllWith f = groupWith f . sortBy (comparing f)

||| Partitions a list into fixed sized sublists.
|||
||| Note: The last list in the result might be shorter than the rest if
||| the input cannot evenly be split into groups of the same size.
|||
||| ```idris example
||| grouped 3 [1..10] === [[1,2,3],[4,5,6],[7,8,9],[10]]
||| ```
public export
grouped : (n : Nat) -> {auto 0 p : IsSucc n} -> List a -> List (List a)
grouped _ [] = []
grouped (S m) (x::xs) = go [<] [<x] m xs
where
go : SnocList (List a) -> SnocList a -> Nat -> List a -> List (List a)
go sxs sx c [] = sxs <>> [sx <>> []]
go sxs sx 0 (x :: xs) = go (sxs :< (sx <>> [])) [<x] m xs
go sxs sx (S k) (x :: xs) = go sxs (sx :< x) k xs

--------------------------------------------------------------------------------
-- Properties
--------------------------------------------------------------------------------
Expand Down

0 comments on commit 7fbbb03

Please sign in to comment.