Difference between fold and reduce?

前端 未结 4 829
囚心锁ツ
囚心锁ツ 2020-12-13 05:12

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 r

4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-13 06:00

    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.

提交回复
热议问题