Trying to learn F# but got confused when trying to distinguish between fold and reduce. Fold seems to do the same thing but takes an extra parameter. Is there a legitimate reason for these two functions to exist or they are there to accommodate people with different backgrounds? (E.g.: String and string in C#)
Here is code snippet copied from sample:
let sumAList list =
List.reduce (fun acc elem -> acc + elem) list
let sumAFoldingList list =
List.fold (fun acc elem -> acc + elem) 0 list
printfn "Are these two the same? %A "
(sumAList [2; 4; 10] = sumAFoldingList [2; 4; 10])
Foldtakes an explicit initial value for the accumulator whilereduceuses the first element of the input list as the initial accumulator value.This means the accumulator and therefore result type must match the list element type, whereas they can differ in
foldas the accumulator is provided separately. This is reflected in the types:In addition
reducethrows an exception on an empty input list.