Skip to content

Instantly share code, notes, and snippets.

@jtbandes
Last active August 29, 2015 14:26
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 jtbandes/d8a600c51fa7e93162fa to your computer and use it in GitHub Desktop.
Save jtbandes/d8a600c51fa7e93162fa to your computer and use it in GitHub Desktop.
// 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