In Javascript there is reduce function which takes function and array, map over the array and return whatever the function return.
For example:
[1, 2, 3].reduce(function(acc, x) {
acc += x
return acc;
}, 0); // 6
In Haskell there is fold which for me do the same:
foldl (+) 0 [1,2,3] -> 6
If i want to create that kind of function as library is it safe to call it fold instead of reduce and is there any difference between the two.
Does both functions the same except the name or there is some difference
I demonstrate with different languages because Js doesnt have foldl function.
Naming is inconsistent, and depends on the language.
In some contexts like Kotlin, reduce
doesn't take an initial value, but fold
does. In Haskell, there's foldl
and foldl1
to differentiate between the two kinds. In Clojure, the same function reduce
has different overloads for taking an initial value, or not taking one.
They're basically describing the same concept, and I've never found any clear difference between the two names.