Skip to content

Instantly share code, notes, and snippets.

@mattpodwysocki
Created February 16, 2017 19:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattpodwysocki/d6a0f518dbe03a93d1828f2030aef844 to your computer and use it in GitHub Desktop.
Save mattpodwysocki/d6a0f518dbe03a93d1828f2030aef844 to your computer and use it in GitHub Desktop.
Implementing folds via left and right
'use strict';
let arr = [1,2,3,4,5];
let fn = (acc, x) => {
console.log(`${acc}-${x}`);
return acc * x;
};
let seed = 1;
/*
foldl :: (a -> b -> a) -> a -> [b] -> a
foldl f a bs =
foldr (\b g x -> g (f x b)) id bs a
*/
function reduceLeft(arr, fn, seed) {
return arr.reduceRight((f, n) => x => f(fn(x, n)), x => x)(seed);
}
/*
foldr :: (b -> a -> a) -> a -> [b] -> a
foldr f a bs =
foldl (\g b x -> g (f b x)) id bs a
*/
function reduceRight(arr, fn, seed) {
return arr.reduce((f, n) => x => f(fn(x, n)), x => x)(seed);
}
reduceLeft(arr, fn, seed);
/*
1-1
1-2
2-3
6-4
24-5
> 120
*/
reduceRight(arr, fn, seed);
/*
1-5
5-4
20-3
60-2
120-1
> 120
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment