You don't see a difference in your example because you chose a function such that for any x1
and x2
:
(acc - x1) - x2 = (acc - x2) - x1
So it doesn't matter in what order you go through the list, you will get the same result.
List construction is an example of function for which it is not the case:
x1 :: (x2 :: acc) <> x2 :: (x1 :: acc)
So the following will yield different results:
List.fold (fun acc x -> x :: acc) [] [1; 2; 3; 4; 5]
// val it : int list = [5; 4; 3; 2; 1]
List.foldBack (fun x acc -> x :: acc) [1; 2; 3; 4; 5] [];;
// val it : int list = [1; 2; 3; 4; 5]
List.fold
starts with an empty result list and goes forward through the input, adding each element to the front of the result list; therefore the final result is in the reverse order.
List.foldBack
, on the other hand, goes backward through the input; so each element newly added to the front of the result list was itself to the front in the original list. So the final result is the same list as the original.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…