Last active
August 29, 2015 14:12
-
-
Save kazk/6d55341c71b95f8e7ba8 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
// [D std.range.chain]: http://dlang.org/phobos/std_range.html#chain | |
/// Concatenates several sequences of same kind into a single one. | |
public func chain<S : SequenceType>(sequences: S...) -> SequenceOf<S.Generator.Element> { | |
return SequenceOf {_ -> GeneratorOf<S.Generator.Element> in | |
var ss = sequences.generate() | |
var g = ss.next()?.generate() | |
return GeneratorOf { | |
if let x = g?.next() { return x } | |
// Must be `while let` not `if let` to handle empty sequence in between | |
while let s = ss.next() { | |
g = s.generate() | |
if let x = g?.next() { return x } | |
} | |
return nil | |
} | |
} | |
} | |
// extension SequenceOf { var array: [T] { return Array(self) } } | |
// chain([0,1,2,3], [4,5,6,7], [8,9,10,11,12]).array | |
//=> [0,1,2,3,4,5,6,7,8,9,10,11,12] | |
// chain([0]).array | |
//=> [0] | |
// chain([0],[],[1]).array | |
//=> [0,1] | |
// chain([0,1,2,3].generate(), [4,5,6,7].generate(), [8,9,10,11,12].generate()).array | |
//=> [0,1,2,3,4,5,6,7,8,9,10,11,12] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment