-
-
Save puttin/3bfe41d04a5fc566a6ee to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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