Skip to content

Instantly share code, notes, and snippets.

@mattt mattt/unzip.swift
Last active Nov 11, 2018

Embed
What would you like to do?
func unzip<S: Sequence, T, U>(_ sequence: S) -> (AnySequence<T>, AnySequence<U>)
where S.Element == (T, U)
{
return (
AnySequence(sequence.lazy.map{ $0.0 }),
AnySequence(sequence.lazy.map{ $0.1 })
)
}
let fibonacci = sequence(first: (0, 1), next: { ($1, $0 + $1) })
let (withZero, withoutZero) = unzip(fibonacci)
withZero // (0, 1, 1, 2, 3, 5, 8, 13, 21, 34 ...
@babbage

This comment has been minimized.

Copy link

babbage commented Nov 11, 2018

A much less complex approach of course is just to map the sequence you want directly, without implementing the unzip function with generics:
let withZero = sequence(first: (0, 1), next:{ ($1, $0 + $1) }).lazy.map{ $0.0 }

Based entirely on your example, not claiming any credit here, just pointing out the most simple path to the result. :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.