Skip to content

Instantly share code, notes, and snippets.

@oisdk
Created August 10, 2015 23:07
Show Gist options
  • Save oisdk/938f261ae48beaa32491 to your computer and use it in GitHub Desktop.
Save oisdk/938f261ae48beaa32491 to your computer and use it in GitHub Desktop.
public struct FilterGenerator<G : GeneratorType> : GeneratorType {
private var generator: G
private let predicate: G.Element -> Bool
public mutating func next() -> G.Element? {
while let next = generator.next() { if predicate(next) { return next } }
return nil
}
}
public struct FilterSequence<S : SequenceType> : SequenceType {
private let sequence : S
private let predicate: S.Generator.Element -> Bool
public func generate() -> FilterGenerator<S.Generator> {
return FilterGenerator(generator: sequence.generate(), predicate: predicate)
}
}
extension LazySequence {
public func filter(includeElement: Generator.Element -> Bool) -> FilterSequence<LazySequence> {
return FilterSequence(sequence: self, predicate: includeElement)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment