I'm trying to write a function that implements foldl in JavaScript. I'm trying to use recursion in the function but not being able to implement it.
var foldl = function(f, acc, array) {
if (array.length == 0) {
return acc;
} else {
return f(array[0], foldl(f, acc, array.slice(-1)));
}
}
console.log(foldl(function(x, y) {
return x + y
}, 0, [1, 2, 3]));
console.log(foldl(function(x,y){return x+y}, 0, [1,2,3]));
Error Message..
RangeError: Maximum call stack size exceeded
Your challenge, as mentioned above, is that you're returning an array of the last element. And you're always returning an array of the last element.
What is missing from the answers above is that they're only good for folding to the right.
For the right case, you can just use .slice(1)
, and that will pull everything after the head.
For the fold left case, you need to specify how far you need to go .slice(0, arr.length - 1)
.
const foldr = (f, acc, arr) => {
if (!arr.length) {
return acc;
} else {
const head = arr[0];
const tail = arr.slice(1);
return foldr(f, f(acc, head), tail);
}
};
foldr((x, y) => x + y, 0, [1, 2, 3])// 6
const foldl = (f, acc, arr) => {
if (!arr.length) {
return acc;
} else {
const head = arr[arr.length - 1];
const tail = arr.slice(0, arr.length - 1);
return foldl(f, f(acc, head), tail);
}
};
foldl((x, y) => x + y, 0, [3, 2, 1]); // 6