Created
December 14, 2015 21:31
-
-
Save hsavit1/3a25879147b6a5b86fbd to your computer and use it in GitHub Desktop.
Fibonacci sequence in Swift
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
| /// Generator for Fibonacci sequence | |
| func fibonacciGenerator() -> AnyGenerator<Int> { | |
| var a = -1 | |
| var b = 1 | |
| return anyGenerator { | |
| let next = a + b | |
| a = b | |
| b = next | |
| return next | |
| } | |
| } | |
| /// Infinite lazy sequence of Fibonacci numbers | |
| let fibs = AnySequence(fibonacciGenerator) | |
| // Print first 20 elements | |
| for n in fibs.prefix(20) { print(n) } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment