Skip to content

Instantly share code, notes, and snippets.

@jakebromberg
Last active August 29, 2015 14:27
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 jakebromberg/f6b27e19abbfd719eaa9 to your computer and use it in GitHub Desktop.
Save jakebromberg/f6b27e19abbfd719eaa9 to your computer and use it in GitHub Desktop.
// generators provide a 'one shot' mechanism for repeatedly computing the next element.
struct FibonacciGenerator<T: IntegerArithmeticType> : GeneratorType {
var num1 : T
var num2 : T
mutating func next() -> T? {
let value = num1
(num1, num2) = (num2, num1 + num2)
return value
}
}
struct FibonacciSequence<T: IntegerArithmeticType> : SequenceType {
let generatorz : () -> FibonacciGenerator<T>
func generate() -> FibonacciGenerator<T> {
return generatorz()
}
}
var fgen = FibonacciGenerator(num1: 1, num2: 1);
let fseq = FibonacciSequence(generatorz: { fgen })
// kaboom, obvs
//for num in fseq {
// print(num)
//}
struct LimitedGenerator<G: GeneratorType> : GeneratorType {
var generator : G
var limit : Int
mutating func next() -> G.Element? {
if let next = generator.next() where limit > 0 {
limit--
return next
} else {
return nil
}
}
}
let fgenLtd = LimitedGenerator(generator: fgen, limit: 10)
let fseqLtd = AnySequence { fgenLtd }
fseqLtd.forEach { print($0) }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment