Skip to content

Instantly share code, notes, and snippets.

@tokland
Last active January 19, 2019 13:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tokland/09583a881c49a8b60a34eadfc7910f32 to your computer and use it in GitHub Desktop.
Save tokland/09583a881c49a8b60a34eadfc7910f32 to your computer and use it in GitHub Desktop.
/* Some monadic and helper functions */
function* pure<T>(value: T): IterableIterator<T> {
yield value;
}
function* concat<T>(...iterators: Array<IterableIterator<T>>): IterableIterator<T> {
for (const iterator of iterators) {
yield* iterator;
}
}
function* pairwise<T>(iterator: IterableIterator<T>): IterableIterator<[T, T]> {
let value: T = iterator.next().value;
while (true) {
const res = iterator.next();
if (res.done) {
break;
} else {
yield [value, res.value];
value = res.value;
}
}
}
/* Fibonacci! */
function* fibonacci(): IterableIterator<number> {
yield* concat(pure(1), pure(2), map(([x, y]) => x + y, pairwise(fibonacci())));
}
/* Example: Let's get the first 10 values */
const fibs = fibonacci();
for (let i = 0; i < 10; i++ ){
console.log(fibs.next().value);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment