Search code examples
f#functional-programmingreducefold

Difference between fold and reduce?


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

Solution

  • Fold takes an explicit initial value for the accumulator while reduce uses 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 fold as the accumulator is provided separately. This is reflected in the types:

    List.fold : ('State -> 'T -> 'State) -> 'State -> 'T list -> 'State
    List.reduce : ('T -> 'T -> 'T) -> 'T list -> 'T
    

    In addition reduce throws an exception on an empty input list.