Skip to content

Instantly share code, notes, and snippets.

@oisdk

oisdk/Sequence.Swift

Last active Aug 29, 2015
Embed
What would you like to do?
extension SequenceType {
var headTail: (Generator.Element, AnySequence<Generator.Element>)? {
var g = self.generate()
return g.next().map{($0, AnySequence{g})}
}
func scan<U>(initial: U, combine: (U, Generator.Element) -> U) -> [U] {
var prev = initial
return self.map{prev = combine(prev, $0); return prev}
}
func scan(combine: (Generator.Element, Generator.Element) -> Generator.Element) -> [Generator.Element]? {
return self.headTail.map{$1.scan($0, combine: combine)}
}
func reduce(combine: (Generator.Element, Generator.Element) -> Generator.Element) -> Generator.Element? {
return self.headTail.map{$1.reduce($0, combine: combine)}
}
func all(condition: Generator.Element -> Bool) -> Bool {
return !self.contains{!condition($0)}
}
}
protocol Lazy: SequenceType {}
extension LazySequence: Lazy {}
extension LazyBidirectionalCollection: Lazy {}
extension LazyForwardCollection: Lazy {}
extension LazyRandomAccessCollection: Lazy {}
extension Lazy {
var headTail: (Generator.Element, LazySequence<AnySequence<Generator.Element>>)? {
var g = self.generate()
return g.next().map{($0, lazy(AnySequence{g}))}
}
func scan<U>(initial: U, combine: (U, Generator.Element) -> U) -> LazySequence<AnyGenerator<U>> {
var (prev, g) = (initial, self.generate())
return lazy( anyGenerator { g.next().map { prev = combine(prev, $0); return prev } } )
}
func scan(combine: (Generator.Element, Generator.Element) -> Generator.Element) -> LazySequence<AnyGenerator<Generator.Element>>? {
return self.headTail.map{$1.scan($0, combine: combine)}
}
func reduce(combine: (Generator.Element, Generator.Element) -> Generator.Element) -> Generator.Element? {
return self.headTail.map{$1.reduce($0, combine: combine)}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.