What's difference between reduce and fold ?
# announcements
y
What's difference between reduce and fold ?
h
fold
is much more general. It allows you to choose what the type of the accumulator is and its initial value
With
reduce
accumulator type is fixed, it is always the same type as the element type.
If for example you want to find the max value in an
IntArray
, you could use
reduce
because you are reducing to the same type (
Int
)
If instead you wanted to count how many times each value occurs in the
IntArray
, you would have to use
fold
cause you are reducing to a
Map<Int, Int>
(or similar structure) and not just simply an
Int
y
So basically fold usage that initial value twice?
s
What do you mean by “usage that initial value twice”
h
No... not sure what you mean. It's really all about the accumulator. In
fold
, you may use any type you want for an accumulator. That's not true in
reduce
, the accumulator type is fixed.
n
fold
relays on a accumulator, its execution is sequential,
reduce
relays on the concept of identity and associativity and does not require operations to be executed in any particular order
so
fold
scans through your collection and appends each value to the accumulator,
reduce
picks any two adjacent values and applies the operation >>replacing<< (but not really) the values with the result then repeats. The difference is that
reduce
can be done in parallel,
fold
not really.
simply speaking
fold
is a line of operations,
reduce
is a tree