Created
September 20, 2015 16:27
-
-
Save ivan-demchenko/4be1038bf95214a011d4 to your computer and use it in GitHub Desktop.
Lazy list comprehension using generator
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
// Inspired by Haskell's `takeWhile (<10000) $ map (^3) [1..]` | |
let nextVal = (x) => x.next().value; | |
function* mList(x = 0) { | |
while(1) yield x++; | |
} | |
function* map(fn, list) { | |
while(1) { | |
yield fn(nextVal(list)); | |
} | |
} | |
function* takeWhile(p, list) { | |
let nv = nextVal(list); | |
while (p(nv)) { | |
yield nv; | |
nv = nextVal(list); | |
} | |
} | |
let tripple = (x) => x * x * x; | |
let lessThan = (x) => (y) => y < x | |
let trippledValuesLessThen100 = takeWhile(lessThan(100), map(tripple, mList(1))); | |
let res = [for (x of trippledValuesLessThen100) x]; | |
console.log(res); // [1,8,27,64] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment