Last active
August 29, 2015 14:24
-
-
Save sveinhal/57a0bc2e2fae6cb064c7 to your computer and use it in GitHub Desktop.
A sequence type that iterates over pairs of the underlying sequence
This file contains 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
import Foundation | |
struct PairGenerator<T: GeneratorType> : GeneratorType { | |
typealias Pair = (first: T.Element?, second: T.Element?) | |
var baseGenerator: T | |
var previousPair: Pair | |
init(_ baseGenerator: T) { | |
self.baseGenerator = baseGenerator | |
self.previousPair = (nil, nil) | |
} | |
mutating func next() -> Pair? { | |
let pair = (first: previousPair.second, second: baseGenerator.next()) | |
previousPair = pair | |
if pair.first == nil && pair.second == nil { | |
return nil | |
} else { | |
return pair | |
} | |
} | |
} | |
extension SequenceType { | |
func pairs() -> GeneratorSequence<PairGenerator<Self.Generator>> { | |
return GeneratorSequence(PairGenerator(generate())) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Given any
SequenceType
this adds a methodpairs()
which returns another kind ofSequenceType
. It lets you iterate over pairs in a sequence, like so: