Last active
November 11, 2018 02:48
-
-
Save mattt/6459d212f3b3756ead821f770577458c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 ... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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. :)