Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
struct RecurrenceRelation<Element>: SequenceType, GeneratorType {
private var prevs: [Element]
private let relat: ([Element], Int) -> Element
private var i: Int = 0
mutating func next() -> Element? {
guard i == prevs.endIndex else { return prevs[i++] }
prevs.append(relat(prevs, i))
prevs.removeAtIndex(0)
return prevs.last
}
init(_ base: [Element], relation: ([Element], Int) -> Element) {
relat = relation
prevs = base
}
}
let fibs = RecurrenceRelation([1, 1]) {
(t, n) in t[n - 1] + t[n - 2]
}
fibs.prefix(10) // [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment