Skip to content

Instantly share code, notes, and snippets.

@oisdk
Created June 17, 2015 12:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oisdk/243be25cfe9fdc57634a to your computer and use it in GitHub Desktop.
Save oisdk/243be25cfe9fdc57634a to your computer and use it in GitHub Desktop.
public struct UniquesGen<G : GeneratorType where G.Element : Hashable> : GeneratorType {
typealias Element = G.Element
private var prevs: Set<Element>
private var g: G
public mutating func next() -> Element? {
return g.next().flatMap{n in prevs.contains(n) ? next() : {prevs.insert(n); return n}()}
}
}
public struct UniquesSeq<S : SequenceType where S.Generator.Element : Hashable> : SequenceType {
typealias Generator = UniquesGen<S.Generator>
private let seq: S
public func generate() -> Generator {
return UniquesGen(prevs: [], g: seq.generate())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment