Instantly share code, notes, and snippets.

Embed
What would you like to do?
// Single-struct version.
// This seems to work just as well as having a custom generator struct.
// I'm not sure if there are other (performance?) implications, however.
struct PrefixSequence<T> : SequenceType
{
let base: AnySequence<T>
let maxLength: Int
init<S : SequenceType where S.Generator.Element == T>(_ base: S, _ maxLength: Int) {
self.base = AnySequence(base)
self.maxLength = maxLength
}
func generate() -> AnyGenerator<T>
{
let generator = base.generate()
var remaining = maxLength
return anyGenerator {
if remaining-- == 0 { return nil }
return generator.next()
}
}
}
extension SequenceType
{
// this could also just return PrefixSequence<Generator.Element>,
// but then callers would have to lazy() it to get map, filter, etc.
func prefix(maxLength: Int) -> LazySequence<PrefixSequence<Generator.Element>>
{
return lazy(PrefixSequence(self, maxLength))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment