Stream: contributing

Topic: List.chunksOf builtin


view this post on Zulip Elias Mulhall (Oct 06 2023 at 21:59):

I've already got a function written for https://github.com/roc-lang/roc/issues/5885, so I'd be happy to make a PR.

This is my first time contributing, so I partially just want to make sure I understand the process. Do I need to do anything on github, or is posting here and making a PR sufficient?

I have one technical question, which is if there are any established patterns for walking every N elements of a list. Here's my current code

chunksOf : List a, Nat -> List (List a)
chunksOf = \list, chunkSize ->
    if chunkSize == 0 || List.len list == 0 then
        []
    else
        chunkIndices = List.range { start: At 0, end: At (List.len list), step: chunkSize }
        chunks = (List.withCapacity (List.len chunkIndices))

        List.walk chunkIndices chunks \state, chunkStartIndex ->
            List.append state (List.sublist list {start: chunkStartIndex, len: chunkSize})

expect chunksOf (List.range {start: At 0, end: At 10}) 0 == []
expect chunksOf [] 5 == []
expect chunksOf [1,2,3,4] 5 == [[1,2,3,4]]
expect chunksOf [1, 2, 3, 4, 5, 6, 7, 8] 3 == [[1, 2, 3], [4, 5, 6], [7, 8]]

chunkIndices is convenient because it does the math for us of determining how many chunks will be in the final list and where each chunk starts, but it's an extra (temporary) array allocation. Would a recursive function be better? Any other ways to do this?

view this post on Zulip Richard Feldman (Oct 07 2023 at 00:38):

posting here and making a PR is sufficient! It's always a good idea to confirm that we definitely want to add the builtin before working on a PR (and in this case I can confirm that we do!) but other than that, there's no other process!

view this post on Zulip Brendan Hansknecht (Oct 07 2023 at 00:47):

As for perf, a tail recursive version would be better, but I wouldn't worry about it too much. Someone can always optimize it in the future.


Last updated: Jul 06 2025 at 12:14 UTC