Last active
August 29, 2015 14:27
-
-
Save jakebromberg/f6b27e19abbfd719eaa9 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
// 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