折叠和缩小之间的区别? [英] Difference between fold and reduce?
问题描述
这里是从样本复制的代码片段:
let sumAList list =
List.reduce(fun acc elem - > acc + elem)list
let sumAFoldingList list =
List.fold(fun acc elem - > acc + elem)0 list
printfn这两个是相同的?%A
(sumAList [2; 4; 10] = sumAFoldingList [2; 4; 10])
/ code>为累加器显式初始值,而
reduce
使用输入列表的第一个元素作为初始累加器值。
这意味着累加器,因此结果类型必须与列表元素类型匹配,而它们可以在 fold
中有所不同,因为累加器是单独提供的。这反映在以下类型中:
List.fold:('State - >'T - >'State) - > '州 - > 'T列表 - > 'State
List.reduce:('T - >'T - >'T) - > 'T列表 - > 'T
另外 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])
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.
这篇关于折叠和缩小之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!