Is there a difference between contraction and contraction

I learn f # from msdn and look and try to reduce and decrease backwards, I can not find the difference, the signature is the same

('T -> 'T -> 'T) -> 'T list -> 'T

and they both throw the same error on an empty list, so why there are 2 of them, there must be some difference

+5
source share
3 answers

Others have already explained the difference - they reduce the elements in a different order.

For most operations that you can use with reduceor reduceBack, the difference does not really matter. In more mathematical terms, if your operation is associative (for example, numerical operations, maximum, minimum or total functions, linking, etc.), then they behave the same.

, , , :

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

, ( , , !)

          reduce        reduceBack
-------------------------------------
tree:       /\              /\
           /\ 3            0 /\
          /\ 2              1 /\
         0  1                2  3
-------------------------------------
flat:    0 1 2 3          0 1 2 3
+8

, MSDN, reduceBack.

reduce , :

f, i0... iN, f (... (f i0 i1) i2...) iN.

reduceBack , :

f, i0... iN, f i0 (... (f iN-1 iN)).

+4

Their main difference is the evaluation procedure. While reducemoving from the first element to the last, it reduceBackgoes in the reverse order. Note that the order between the current item and the battery also changes to reduceBack.

A case in point could be:

let last xs = List.reduce (fun _ x -> x) xs   
let first xs = List.reduceBack (fun x _ -> x) xs
+3
source

All Articles