Skip to content

Instantly share code, notes, and snippets.

@apense
Created June 23, 2015 18:23
Show Gist options
  • Save apense/264fde24ef3b587aace2 to your computer and use it in GitHub Desktop.
Save apense/264fde24ef3b587aace2 to your computer and use it in GitHub Desktop.
Fibonacci numbers and Factorials as iterators
iterator factorials(k: int): int =
## Yields from 0! to k! as an iterator
var (n, f) = (0, 1)
yield 1 # for 0!
while n < k:
yield f
n = n + 1; f = f * (n + 1)
iterator fibonacci(cap: int): int =
## Yields Fibonacci numbers <= `cap` as an iterator
var (a, b) = (0, 1)
while a <= cap:
yield a
let tmp = a
a = b
b = tmp + b
for f in factorials(10):
echo f
for f in fibonacci(1000):
echo f
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment