折叠和减少的区别? [英] Difference between fold and reduce?

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

问题描述

尝试学习 F#,但在尝试区分 折叠减少.折叠似乎做了同样的事情,但需要一个额外的参数.这两个功能的存在是否有正当理由,或者它们是为了适应不同背景的人?(例如:C# 中的字符串和字符串)

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 为累加器采用显式初始值,而 reduce 使用输入列表的第一个元素作为初始累加器值.

Fold takes an explicit initial value for the accumulator while reduce uses the first element of the input list as the initial accumulator value.

这意味着累加器和结果类型必须与列表元素类型匹配,而它们在 fold 中可以不同,因为累加器是单独提供的.这体现在类型上:

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

此外,reduce 会在空输入列表上抛出异常.

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

这篇关于折叠和减少的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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