Created
June 22, 2017 04:57
-
-
Save abiodun0/9b8aeb80a39ceb29f1232be0a4bd3682 to your computer and use it in GitHub Desktop.
InfinitList javascript
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
| //repeat :: a -> [a] | |
| var repeat = function(a){ | |
| return [a].concat( repeat(a) ); | |
| } | |
| // take :: Int -> [a] -> [a] | |
| var take = function(n, a){ | |
| if(a.length == 0 || n <= 0 ) return []; | |
| return a[0].concat( take( n - 1, a.slice(1) ) ); | |
| } | |
| var r = take(5, repeat(5)); | |
| console.log(r); | |
| // You can’t make an infinite list that way because JavaScript is an eager language. It will just keep building the list forever | |
| // However you can use generators | |
| var repeat = function *(a) { | |
| while (true) yield a | |
| } | |
| var take = function *(n, a) { | |
| for (var x of a) { | |
| if (n == 0) break | |
| yield x | |
| n-- | |
| } | |
| } | |
| var r = take(5, repeat(5)) | |
| console.log([... r]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment