Skip to content

Instantly share code, notes, and snippets.

@abiodun0
Created June 22, 2017 04:57
Show Gist options
  • Select an option

  • Save abiodun0/9b8aeb80a39ceb29f1232be0a4bd3682 to your computer and use it in GitHub Desktop.

Select an option

Save abiodun0/9b8aeb80a39ceb29f1232be0a4bd3682 to your computer and use it in GitHub Desktop.
InfinitList javascript
//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