Last active
January 19, 2019 13:37
-
-
Save tokland/09583a881c49a8b60a34eadfc7910f32 to your computer and use it in GitHub Desktop.
This file contains 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
/* 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