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?
You can use List.map2
like this:
List.map2 [1,2] [3,4] \x, y -> [x,y]
Thank you
@Ashley Davis, just mentioning for completeness. If you're after a List
of List
s 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 )*
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