I'd rename `gen` to `generator` so that in the while loop, you can do:
while var gen = generator {
...
}
That way, you don't have to force unwrap gen.
This doesn't work, since gen.next()
only mutates the local variable gen
I'd rename gen
to generator
so that in the while loop, you can do:
I would opt to use while let instead of explicitly checking if gen is nil:
while let gen = generator {
...
}
That way, you don't have to force unwrap gen.
You need to declare generator
and the elements of queue
as AnyGenerator
s for this to work. That way they are ensured to be reference types and gen
and generator
refer to the same instance.
while// letCurrent _generator, =or gen`nil` {
if all sequences are exhausted:
var generator: AnyGenerator<S.Generator.Element>? = AnyGenerator(seq.generate())
}// Queue of generators for sequences which still have to be enumerated:
var queue: [AnyGenerator<S.Generator.Element>] = []
gengenerator = queue.popFirst()
This one might be going a bit far because we're extending Array just to get rid of 3 lines, but I really think it improves readability. In the end it's you'reyour call.
func sequentialFlatten<S : SequenceType>(seq : S, children : (S.Generator.Element) -> S) -> AnySequence<S.Generator.Element> {
return AnySequence {
() -> AnyGenerator<S.Generator.Element> in
// Current generator, or `nil` if all sequences are exhausted:
var gengenerator: SAnyGenerator<S.Generator.Element>? = AnyGenerator(seq.generate())
// Queue of generators for sequences which still have to be enumerated:
var queue: [S[AnyGenerator<S.Generator]Generator.Element>] = []
return AnyGenerator {
while let _gen = gengenerator {
if let next = gen?.next() {
queue.append(AnyGenerator(children(next).generate()))
return next
}
// Current generator is empty, try to deque next one:
gengenerator = queue.popFirst() // `nil` if queue is empty
}
return nil
}
}
}