Stream: beginners

Topic: Zipping two lists


view this post on Zulip Ashley Davis (Mar 30 2024 at 23:12):

I'm just getting started with Roc and trying to work out how to zip two lists together, the code will look something like:

List.zip [1, 2] [3, 4]

And the result should look like this:

[[1,3], [2,4]]

I couldn't find the zip function.

How should I do this?

view this post on Zulip Isaac Van Doren (Mar 31 2024 at 00:10):

You can use List.map2 like this:

List.map2 [1,2] [3,4] \x, y -> [x,y]

view this post on Zulip Ashley Davis (Mar 31 2024 at 05:31):

Thank you

view this post on Zulip Hristo (Mar 31 2024 at 18:11):

@Ashley Davis, just mentioning for completeness. If you're after a List of Lists representation, then the underlying element type - both input and output - can be only one (i.e., the resulting sub-lists have to be homogeneous lists, just as the input lists do).

If a tuple would work equally well for you, then the input inter-list types don't have to be the same (since the resulting tuple can contain heterogeneous types, by definition):

» List.map2 [1,2] ["A","B"] \x, y -> (x,y)

[(1, "A"), (2, "B")] : List ( Num *, Str )*

view this post on Zulip Brendan Hansknecht (Mar 31 2024 at 18:24):

Tuples will also generally be more performant and probably should be preferred for this use case.


Last updated: Jul 06 2025 at 12:14 UTC