折叠和缩小之间的区别? [英] Difference between fold and reduce?

查看:104
本文介绍了折叠和缩小之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图学习F#,但试图区分 fold 减少。折叠似乎做同样的事情,但需要一个额外的参数。这两个功能是否存在合法的原因,或者他们是否适应不同背景的人? (例如:C#中的字符串和字符串)

这里是从样本复制的代码片段:

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆