Zulip Chat Archive

Stream: Is there code for X?

Topic: Split list to chunks of specified size


Daniel Weber (Sep 20 2024 at 03:15):

Suppose I have a list l : List α, and a sz : List Nat such that sz.sum = l.length. How can I split l to chunks according to the sizes specified by sz? For example, for l = [a, b, c, d], sz = [1,0,0,2,0,1] I want to get [[a], [], [], [b, c], [], [d]]

Bryan Gin-ge Chen (Sep 20 2024 at 03:54):

Something like this?

def foo : List α  List Nat  List (List α)
| _, [] => []
| x, n::ns =>
  let (x0, x1) := x.splitAt n
  x0 :: foo x1 ns

#eval foo [0,1,2,3] [1,0,0,2,0,1] -- [[0], [], [], [1, 2], [], [3]]

Daniel Weber (Sep 20 2024 at 03:59):

Yes, thanks

Kim Morrison (Sep 20 2024 at 04:12):

Someone was recently writing some API for run length encoding. Perhaps it would be useful to see where that got to.

Daniel Weber (Sep 23 2024 at 13:58):

What would be a good file in Mathlib for this definition?

Kim Morrison (Sep 24 2024 at 00:59):

If it's called List.splitLengths, then Mathlib.Data.List.SplitLengths?

Daniel Weber (Sep 27 2024 at 12:26):

#17191

Kim Morrison (Sep 28 2024 at 02:57):

Daniel Weber said:

#17191

:writing:


Last updated: May 02 2025 at 03:31 UTC