Created
February 16, 2017 19:26
-
-
Save mattpodwysocki/d6a0f518dbe03a93d1828f2030aef844 to your computer and use it in GitHub Desktop.
Implementing folds via left and right
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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