Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add sequtils.unzip to complement sequtils.zip #13429

Merged
merged 4 commits into from
Feb 20, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@
- Added `wrapnils` module for chains of field-access and indexing where the LHS can be nil.
This simplifies code by reducing need for if-else branches around intermediate maybe nil values.
E.g. `echo ?.n.typ.kind`
- Added `minIndex` and `maxIndex` to the `sequtils` module
- Added `minIndex`, `maxIndex` and `unzip` to the `sequtils` module.
- Added `os.isRelativeTo` to tell whether a path is relative to another
- Added `resetOutputFormatters` to `unittest`

Expand Down
15 changes: 15 additions & 0 deletions lib/pure/collections/sequtils.nim
Original file line number Diff line number Diff line change
Expand Up @@ -281,6 +281,21 @@ when (NimMajor, NimMinor) <= (1, 0):
else:
zipImpl(s1, s2, seq[(S, T)])

proc unzip*[S, T](s: openArray[(S, T)]): (seq[S], seq[T]) {.since: (1, 1).} =
## Returns a tuple of two sequences split out from a sequence of 2-field tuples.
runnableExamples:
let
zipped = @[(1, 'a'), (2, 'b'), (3, 'c')]
unzipped1 = @[1, 2, 3]
unzipped2 = @['a', 'b', 'c']
assert zipped.unzip() == (unzipped1, unzipped2)
assert zip(unzipped1, unzipped2).unzip() == (unzipped1, unzipped2)
result[0] = newSeqOfCap[S](s.len)
result[1] = newSeqOfCap[T](s.len)
for elem in s:
kaushalmodi marked this conversation as resolved.
Show resolved Hide resolved
result[0].add(elem[0])
result[1].add(elem[1])

proc distribute*[T](s: seq[T], num: Positive, spread = true): seq[seq[T]] =
## Splits and distributes a sequence `s` into `num` sub-sequences.
##
Expand Down