Last active
October 27, 2020 22:48
-
-
Save gabefinch/1360ebdb9e7a0dda02a1cf63a6c271cf 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
function nums(n = 1) { | |
return { first: n, rest: () => nums(n + 1) }; | |
} | |
nums().first; // => 1 | |
function take(stream, n) { | |
if (n <= 0) return []; | |
else { | |
const { first, rest } = stream(); | |
return [first].concat(take(rest, n - 1)); | |
} | |
} | |
take(nums, 5); // => [1, 2, 3, 4, 5] | |
function nth(stream, n) { | |
if (n < 0) return null; | |
const { first, rest } = stream(); | |
if (n === 0) return first; | |
else return nth(rest, n - 1); | |
} | |
nth(nums, 100); // => 101 | |
function odds(n = 1) { | |
return { first: n, rest: () => nums(n + 2) }; | |
} | |
// function odds(n = 0) { | |
// return { first: 2 * n + 1, rest: () => odds(n + 1) }; | |
// } | |
take(odds, 5); // => [1, 3, 5, 7, 9] | |
function squares(n = 0) { | |
return { first: (n + 1) ** 2, rest: () => squares(n + 1) }; | |
} | |
// function squares(n = 1) { | |
// return { first: n * n, rest: () => squares(n + 1) }; | |
// } | |
take(squares, 5); // => [1, 4, 9, 16, 25] | |
function flipFlop(n = 0) { | |
return { first: n, rest: () => flipFlop(n === 0 ? 1 : 0) }; | |
} | |
// function flipFlop(n = 0) { | |
// return { first: n % 2, rest: () => flipFlop(n + 1) }; | |
// } | |
take(flipFlop, 5); // => [0, 1, 0, 1, 0] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment