Title
y

Yogesh Gosavi

11/30/2018, 4:27 PM
What's difference between reduce and fold ?
h

hudsonb

11/30/2018, 4:30 PM
``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

Yogesh Gosavi

11/30/2018, 4:41 PM
So basically fold usage that initial value twice?
s

Shawn

11/30/2018, 5:28 PM
What do you mean by “usage that initial value twice”
h

hudsonb

11/30/2018, 5:29 PM
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

nekomatic

11/30/2018, 5:31 PM
``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