Skip to content

Instantly share code, notes, and snippets.

@MarkusPfundstein
Created October 1, 2016 13:58
Show Gist options
  • Save MarkusPfundstein/c9dd880b50f90df12d6af6141e03e1e6 to your computer and use it in GitHub Desktop.
Save MarkusPfundstein/c9dd880b50f90df12d6af6141e03e1e6 to your computer and use it in GitHub Desktop.
(partly) lazy list comprehensions js using ramda and generators
//take((e, a) => e+a*a, when(isEven, xs), when(isOdd, ys))
//take((e, a) => e+a*a, [when(isEven, xs), ys])
const R = require('ramda');
// not lazy
const flatxprod = (x, y) => R.map(R.flatten, R.xprod(x, y));
function * nprod(...args) {
function * rec(accum, xs) {
if (xs.length == 0) {
return yield * accum;
} else {
return yield * rec(flatxprod(R.head(xs), accum), R.tail(xs));
}
}
const xs = R.reverse(args);
return yield * rec(R.head(xs), R.tail(xs));
};
const when = R.filter;
function * comp(f, ...arrays) {
for (let e of nprod(...arrays)) {
yield f(...e);
}
};
const isEven = n => n % 2 === 0;
const isOdd = n => R.not(isEven(n));
const notNull = n => n != null;
const [...t] = comp((a,b,c) => a + b +c,
when(isEven, [1,2,3,4,5,6,7,8]),
when(isOdd, [1,2,3,4]),
when(notNull, [1,2,3,null,null,4]));
console.log(t);
/* [ 4,
5,
6,
7,
6,
7,
8,
9,
6,
7,
8,
9,
8,
9,
10,
11,
8,
9,
10,
11,
10,
11,
12,
13,
10,
11,
12,
13,
12,
13,
14,
15 ]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment