Skip to content

Instantly share code, notes, and snippets.

@kghost
Created December 31, 2018 15:24
Show Gist options
  • Save kghost/b001d39b6c6b541a289774bf137f2da8 to your computer and use it in GitHub Desktop.
Save kghost/b001d39b6c6b541a289774bf137f2da8 to your computer and use it in GitHub Desktop.
function unfold(p, f, g, seed, reduce, tailgen) {
function recursive(iter) {
if (p(iter)) return tailgen(iter);
return reduce(f(iter), recursive(g(iter)));
}
return recursive(seed);
}
function sum(a) {
return unfold(
([iter, value]) => value.done,
([iter, value]) => value.value,
([iter, value]) => [iter, iter.next()],
(() => { const iter = a[Symbol.iterator](); return [iter, iter.next()]; })(),
(head, tail) => head + tail,
([iter, value]) => 0,
);
}
console.log(sum([1,2,3]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment