List.fold和List.foldBack之间的区别的示例 [英] Example of the difference between List.fold and List.foldBack

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

问题描述

我对List.foldList.foldBack之间的区别的理解是,foldBack以相反的顺序遍历其列表.这两个函数都会从列表中的项目中累积结果.

My understanding of the difference between List.fold and List.foldBack is that foldBack iterates over its list in a reverse order. Both functions accumulate a result from the items in the list.

我很难提出一个好的例子,在该例子中最好将foldBack放在列表上.在我提出的示例中,如果函数逻辑执行相同的操作,则对于fold和foldBack而言,结果都是相同的.

I'm having trouble coming up with a good example where it is preferable to foldBack over a list. In the examples I have come up with, the results are the same for both fold and foldBack, if the function logic does the same thing.

[<Fact>]
let ``List.foldBack accumulating a value from the right to the left``() =
    let list = [1..5]       
    let fFoldBack x acc =
        acc - x

    let fFold acc x =
        acc - x

    let foldBackResult = List.foldBack fFoldBack list 0
    let foldResult = List.fold fFold 0 list

    Assert.Equal( -15, foldBackResult ) //  0 - 5 - 4 - 3 - 2 - 1
    Assert.Equal( -15, foldResult ) //      0 - 1 - 2 - 3 - 4 - 5

推荐答案

您在示例中看不到任何差异,因为您选择的函数对于任何x1x2:

You don't see a difference in your example because you chose a function such that for any x1 and x2:

(acc - x1) - x2 = (acc - x2) - x1

因此,以何种顺序浏览列表并不重要,您将获得相同的结果.

So it doesn't matter in what order you go through the list, you will get the same result.

列表构造是函数的一个示例,并非如此:

List construction is an example of function for which it is not the case:

x1 :: (x2 :: acc) <> x2 :: (x1 :: acc)

因此以下内容将产生不同的结果:

So the following will yield different results:

List.fold (fun acc x -> x :: acc) [] [1; 2; 3; 4; 5]
// val it : int list = [5; 4; 3; 2; 1]

List.foldBack (fun x acc -> x :: acc) [1; 2; 3; 4; 5] [];;
// val it : int list = [1; 2; 3; 4; 5]

List.fold从一个空的结果列表开始,一直到输入,将每个元素添加到结果列表的前面;因此最终结果是相反的顺序.

List.fold starts with an empty result list and goes forward through the input, adding each element to the front of the result list; therefore the final result is in the reverse order.

List.foldBack通过输入后退;因此,新添加到结果列表最前面的每个元素本身都位于原始列表的最前面.因此,最终结果与原始列表相同.

List.foldBack, on the other hand, goes backward through the input; so each element newly added to the front of the result list was itself to the front in the original list. So the final result is the same list as the original.

这篇关于List.fold和List.foldBack之间的区别的示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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