Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there any difference between reduce and reduceBack

Tags:

.net

f#

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

like image 822
Omu Avatar asked Jun 11 '12 09:06

Omu


People also ask

What is the difference between Reduce and reuse?

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).

What are examples of reduce?

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.

What do you mean by reduced?

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.

Is there any difference between Reduce and decrease?

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.


1 Answers

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
like image 171
Tomas Petricek Avatar answered Oct 23 '22 06:10

Tomas Petricek