Last active
August 29, 2015 14:26
-
-
Save jtbandes/d8a600c51fa7e93162fa to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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