On Github codemiller / welcome-to-the-fold
Katie Miller (@codemiller)OpenShift Developer Advocate at Red Hat
var list = [3, 1, 7, 13, 5, 11, 2]; var acc = 0; for (var i = 0; i < list.length; i++) { acc = acc + list[i]; } console.log(acc); // 42 var sum = function (list) { var acc = 0; for (var i = 0; i < list.length; i++) { acc = acc + list[i]; } return acc; }; sum(list); // 42
var reverse = function (list) { var acc = []; for (var i = 0; i < list.length; i++) { acc = [list[i]].concat(acc); } return acc; }; reverse(list); // [2, 11, 5, 13, 7, 1, 3] var reverse = function (list) { var acc = []; for (var i = 0; i < list.length; i++) { acc = [list[i]].concat(acc); } return acc; }; reverse(list); // [2, 11, 5, 13, 7, 1, 3]
var sum = function (acc, list) { if (list.length == 0) { return acc; } return sum(list.slice(1), acc + list[0]); }; sum(list, 0); // 42
var reverse = function (acc, list) { if (list.length == 0) { return acc; } return reverse(list.slice(1), [list[0]].concat(acc)); }; reverse(list, []); // [2, 11, 5, 13, 7, 1, 3]
var fold = function (func, acc, list) { for(var i = 0; i < list.length; i++) { acc = func(acc, list[i]); } return acc; };
var fold = function (func, acc, list) { if (list.length == 0) { return acc; } return fold(func, func(acc, list[0]), list.slice(1)); };
var sum = function (list) { return fold(function (acc, elem) { return acc + elem; }, 0, list); }; var reverse = function (list) { return fold(function (acc, elem) { return [elem].concat(acc); }, [], list); };
var map = function (func, list) { return fold(function (acc, elem) { return acc.concat([func(elem)]); }, [], list); }; map(function (elem) { return elem + 1; }, [1, 2, 3]); // [2, 3, 4]
var filter = function (pred, list) { return fold(function (acc, elem) { return pred(elem) ? acc.concat([elem]) : acc; }, [], list); }; filter(function (elem) { return elem % 2 == 0; }, [1, 2, 3]); // [2]
Applies a combining function to each element of a listrecursive data structure and a partial result to build a single value
Fold Left versus Right refers to associativity, not processing order
fold(function (func, elem) { return function (acc) { return func([elem].concat(acc)); }; }, identity, [1, 2, 3])([]); // [1, 2, 3] var identity = function (value) { return value; };
Some view Fold Left as "the fundamental list iterator", and Fold Right as "the fundamental list recursion operator".
It can be useful to view Fold Right as a structural transformation on a list:
Katie Miller (@codemiller)OpenShift Developer Advocate at Red Hat