I'm learning f# from msdn and looking and trying out the reduce and reduce back, I can't find any difference, the signature is the same
('T -> 'T -> 'T) -> 'T list -> 'T
and they both throw same error on empty list, so why is there 2 of them, there should be some difference
Reduce means to cut back on the amount of trash we generate. Reuse means to find new ways to use things that otherwise would have been thrown out. Recycle means to turn something old and useless (like plastic milk jugs) into something new and useful (like picnic benches, playground equipment and recycling bins).
Examples of reduction include canceling unwanted magazine subscriptions and eating less energy-intensive food. Turning off the water during teeth brushing rather than leaving it running for the full two minutes is another example of reduction.
1 : to make smaller in size, amount, or number reduce the number of accidents especially : to lose weight by dieting. 2 : to bring to a specified state or condition. 3a : to lower in grade or rank : demote. b : to be driven by poverty or need was reduced to begging. c : to lessen the strength of.
The biggest difference between them is that "decrease" is always referring specifically to a big something becoming a smaller something, whereas "reduce" can refer to changes in state or condition too.
Others already explained the difference - they reduce elements in a different order.
For most of the operations that you can use with reduce
or reduceBack
, the difference does not actually matter. In more mathematical terms, if your operation is associative (such as numeric operations, max, min or sum functions, list concatenation, etc.) then the two behave the same.
An example where you can nicely see the difference is building a tree, because that exactly shows how the evaluation works:
type Tree =
| Leaf of int
| Node of Tree * Tree
[ for n in 0 .. 3 -> Leaf n]
|> List.reduce (fun a b -> Node(a, b))
[ for n in 0 .. 3 -> Leaf n]
|> List.reduceBack (fun a b -> Node(a, b))
Here are the two trees that you get as the result (but note that if you flatten them, then you get the same list!)
reduce reduceBack
-------------------------------------
tree: /\ /\
/\ 3 0 /\
/\ 2 1 /\
0 1 2 3
-------------------------------------
flat: 0 1 2 3 0 1 2 3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With