Created
April 6, 2018 05:31
-
-
Save juri/3c4c4cf66364f2936186d73bb7d2182c to your computer and use it in GitHub Desktop.
Pairwise sequence method for Swift
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
extension Sequence { | |
/// `[e1, e2, …, eN]` → `[(nil, e1), (e1, e2), …, (eN-1, eN), (eN, nil)]` | |
func pairwise() -> UnfoldSequence<(Self.Element?, Self.Element?), ((Self.Element?, Self.Element?)?, Bool)> { | |
var iter = self.makeIterator() | |
var next1: Element? = nil | |
var next2 = iter.next() | |
return Swift.sequence(first: (next1, next2)) { prevpair -> (Element?, Element?)? in | |
guard let nv2 = next2 else { return nil } | |
next1 = nv2 | |
next2 = iter.next() | |
return (next1, next2) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment