Created
June 25, 2014 21:43
-
-
Save ColinEberhardt/af7c4bca378fe0333f1f to your computer and use it in GitHub Desktop.
A demonstration of Swift sequences
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
// a demonstration of Swift sequences | |
// a sequence that lazily creates a Fibonacci sequence | |
class Fibonacci : Sequence { | |
let id:String | |
init(_ id: String) { | |
self.id = id; | |
} | |
func generate() -> GeneratorOf<Int> { | |
var current = -1, last = 0 | |
return GeneratorOf<Int> { | |
if current == -1 { | |
current = 0 | |
} else if current == 0 { | |
current = 1 | |
} else { | |
var next = last + current | |
last = current | |
current = next | |
} | |
println("\(self.id) - \(current)") | |
return current | |
} | |
} | |
} | |
extension SequenceOf { | |
// a skip extension, that skips the first 'n' | |
// items in a sequence | |
func skip (n:Int) -> SequenceOf<T> { | |
var generator = self.generate(); | |
for _ in 0..n { | |
println("skipped") | |
generator.next() | |
} | |
return SequenceOf(generator) | |
} | |
} | |
// odd fibonacci numbers | |
let evenNumbers = filter(Fibonacci("#1")) { $0 % 2 == 0} | |
// even fibonacci numbers | |
let oddNumbers = filter(Fibonacci("#2")) { $0 % 2 == 1} | |
// zipped and skipped! | |
var zipped = SequenceOf(Zip2(oddNumbers, evenNumbers)) | |
.skip(2).generate() | |
// output the first few results | |
for _ in 1...2 { | |
println(zipped.next()) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment